| How would you reverse bits of ... | |||||||
|
30 Day Risk-Free Guarantee:
100% money back if you're unsatisfied. Book (308 Pages):
![]() Video (One Hour):
![]() Resume Review (24 - 48hr)
All Products / Services
|
|||||||
How would you reverse bits of an integer in an optimized way suitable for an embedded system?
12
the question is to reverse the bits i.e. input 11110000 output : 00001111
the solution provided above is a toggle which can be done with operator ~
int toggle (int x) { return ~x;)
use lookup table to store reversed bits of every possible combination in a 8-bit field, so your lookup table is O(1) in memory with 256 elements. then:
int input,result;
result=((table[input&0xff]<<24)|(table[(input>>8)&0xff]<<16)|(table[(input>>16)&0xff]<<8)|(table[(input>>24)&0xff]));
return result;
its an embedded system.. i dont think keeping a table in memory is a good idea.
graphics.stanford.edu/~seander/bithacks.html
unsigned int v; // input bits to be reversed
unsigned int r = v; // r will be reversed bits of v; first get LSB of v
int s = sizeof(v) * CHAR_BIT - 1; // extra shift needed at end
for (v >>= 1; v; v >>= 1)
{
r <<= 1;
r |= v & 1;
s--;
}
r <<= s; // shift when v's highest bits are zero
int reverser (int in) {int out = 0;
int m = 0x8000;
int tmp = 0;for (int i=0; in!=0; i++) {
tmp = in & m;
in = in<<1;
out = (tmp<<i) + out;
}return out;
}
If you don't wanna use a table in memory, there is one more way to do this.
void reverse(int x)
{
// assume 32-bit number
m = 0x55555555; // 1-bit swap
x = ((x & m) << 1) | ((x & ~m) >> 1);
m = 0x33333333; // 2-bits swap
x = ((x & m) << 2) | ((x & ~m) >> 2);
m = 0x0f0f0f0f; // 4-bits swap
x = ((x & m) << 4) | ((x & ~m) >> 4);
m = 0x00ff00ff; // 8-bits swap
x = ((x & m) << 8) | ((x & ~m) >> 8);
x = (x << 16) | (x >> 16); // 16-bits swap
}
Source from stanford/bithacks.html
Recursive version:
int maskarr[] = { 0x55555555, 0x33333333, 0x0f0f0f0f, 0x00ff00ff };
int RecursiveReverse(int x, int i) {
int m;
int p = 1 << i;
if ( i == 4 ) {
return ( x << p ) | ( x >> p);
}
m = maskarr[ i ];
x = ((x & m) << p) | ((x & ~m) >> p);
return RecursiveReverse(x, ++i);
}
Keep in memory that size of int is not known.
Thanks,
NNS Chowdary (+91 959 1234 239)
/*swapping function for byte data type. The logic here is Iam extracting two bits at the same time and swapping them,then oring them and storing them in char variable res
*/
void swap_bits ( int no ) {
char up,lo,res ;
char and = 0x01 ;
for ( int i = 0 ; i < 8 ; i++ ) {
lo = val & and ;
and = shift_bits_lo ( and, 7 - i ) ;
up = val & and ;
and = shift_bits_hi ( and, 7 - i ) ;
for ( int j = 7 - i ; j > 0 ; j++ ) {
up = up >> j ;
lo = lo << j ;
}
res = up | lo ;
}
no = res ;
}
char shift_bits_lo ( char no , int shift) {
while ( shift > 0 )
no = no << shift ;
return no ;
}
char shift_bits_hi ( char no , int shift ) {
while ( shift > 0 )
no = no >> shift ;
return no ;
}
xor the bits with ff.
example : 0000 0011
1111 1111
------------(XOR)
1111 1100