Qualcomm Interview Question
Software Engineer / Developersunsigned int
reverse(register unsigned int x)
{
x = (((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1));
x = (((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2));
x = (((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4));
x = (((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8));
return((x >> 16) | (x << 16));
}
<pre lang="" line="1" title="CodeMonkey54315" class="run-this">/* I tried this. It works */
char ReverseUint8 ( char x)
{
char y = 0;
int i;
unsigned char var = 0x01;
unsigned char var_f = 0x80;
for ( i = 0 ; i < 8 ; i++)
{
if ( x & var )
{
y |= var_f;
}
var = var<<1;
var_f = var_f>>1;
// printf("\n x = %d , y = %d ",x, y);
}
return y;
}</pre><pre title="CodeMonkey54315" input="yes">
</pre>
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
char str[10];
cout<<"\nEnter A String\n";
cin>>str;
char *ptr;
int len=0;
for(ptr=str;*ptr!='\0';ptr++,len++);
cout<<"String Length Is: "<<len<<"\n";
cout<<"\Reverse String: ";
for(--ptr;ptr>=str;ptr--)
cout<<*ptr;
getch();
}
Reverse the bits in a byte with 3 operations (64-bit multiply and modulus division):
unsigned char b; // reverse this (8-bit) byte
b = (b * 0x0202020202ULL & 0x010884422010ULL) % 1023;
The multiply operation creates five separate copies of the 8-bit byte pattern to fan-out into a 64-bit value. The AND operation selects the bits that are in the correct (reversed) positions, relative to each 10-bit groups of bits. The multiply and the AND operations copy the bits from the original byte so they each appear in only one of the 10-bit sets. The reversed positions of the bits from the original byte coincide with their relative positions within any 10-bit set. The last step, which involves modulus division by 2^10 - 1, has the effect of merging together each set of 10 bits (from positions 0-9, 10-19, 20-29, ...) in the 64-bit value. They do not overlap, so the addition steps underlying the modulus division behave like or operations.
unsigned int
- Anonymous July 18, 2010reverse_8bit(register unsigned int x)
{
x = (((x & 0xaa) >> 1) | ((x & 0x55) << 1));
x = (((x & 0xccc) >> 2) | ((x & 0x333) << 2));
x = (((x & 0xf0) >> 4) | ((x & 0x0f) << 4));
return x;
}
}