440,180 Members | 1,016 Online
Need help? Post your question and get tips & solutions from a community of 440,180 IT Pros & Developers. It's quick & easy.

# Reversing Bit Order.. i.e. MSB becomes bit 0, LSB becomes bit 15

 P: n/a Anyone know of an efficient way of reversing the bits of a word?? Aug 18 '07 #1
7 Replies

 P: n/a On Aug 17, 5:36 pm, benn...@hotmail.com wrote: Anyone know of an efficient way of reversing the bits of a word?? htons() <-ntohs() Aug 18 '07 #2

 P: n/a be*****@hotmail.com wrote: Anyone know of an efficient way of reversing the bits of a word?? Not portably, some instructions sets may have a quick way to do this, otherwise shift and add. -- Ian Collins. Aug 18 '07 #3

 P: n/a std::bitset::digitsBit s( num ); cout<<"size_t num="<

 P: n/a be*****@hotmail.com wrote: Anyone know of an efficient way of reversing the bits of a word?? Reverse all the bits in a 32 bit word: n = ((n > 1) & 0x55555555) | ((n << 1) & 0xaaaaaaaa) ; n = ((n > 2) & 0x33333333) | ((n << 2) & 0xcccccccc) ; n = ((n > 4) & 0x0f0f0f0f) | ((n << 4) & 0xf0f0f0f0) ; n = ((n > 8) & 0x00ff00ff) | ((n << 8) & 0xff00ff00) ; n = ((n >16) & 0x0000ffff) | ((n << 16) & 0xffff0000) ; Aug 18 '07 #5

 P: n/a Wow! That is slick, and it worked nicely too! Not quite sure how it works, but for 16 bits, would it work something like: n = ((n > 1) & 0x5555) | ((n << 1) & 0xaaaa) ; n = ((n > 2) & 0x3333) | ((n << 2) & 0xcccc) ; n = ((n > 4) & 0x0f0f) | ((n << 4) & 0x0f0f) ; Juha Nieminen wrote: be*****@hotmail.com wrote: Anyone know of an efficient way of reversing the bits of a word?? Reverse all the bits in a 32 bit word: n = ((n > 1) & 0x55555555) | ((n << 1) & 0xaaaaaaaa) ; n = ((n > 2) & 0x33333333) | ((n << 2) & 0xcccccccc) ; n = ((n > 4) & 0x0f0f0f0f) | ((n << 4) & 0xf0f0f0f0) ; n = ((n > 8) & 0x00ff00ff) | ((n << 8) & 0xff00ff00) ; n = ((n >16) & 0x0000ffff) | ((n << 16) & 0xffff0000) ; Aug 20 '07 #6

 P: n/a On Aug 21, 12:55 am, benn...@hotmail.com wrote: Wow! That is slick, and it worked nicely too! Not quite sure how it works, but for 16 bits, would it work something like: n = ((n > 1) & 0x5555) | ((n << 1) & 0xaaaa) ; n = ((n > 2) & 0x3333) | ((n << 2) & 0xcccc) ; n = ((n > 4) & 0x0f0f) | ((n << 4) & 0x0f0f) ; Textbook example; and please dont top-post... template T reverseBits(T inval){ T retval=0; numberofbits= sizeof(T) * CHAR_BITS; for ( int i = 0; i < numberofbits; ++i ) { retval = ( retval << 1 ) | ( inval & 1 ); inval >>= 1; } return retval; } Aug 20 '07 #7

 P: n/a be*****@hotmail.com wrote: Wow! That is slick, and it worked nicely too! Not quite sure how it works, but for 16 bits, would it work something like: n = ((n > 1) & 0x5555) | ((n << 1) & 0xaaaa) ; n = ((n > 2) & 0x3333) | ((n << 2) & 0xcccc) ; n = ((n > 4) & 0x0f0f) | ((n << 4) & 0x0f0f) ; I believe it additionally needs: n = ((n > 8) & 0x00ff) | ((n << 8) & 0xff00) ; Aug 22 '07 #8

### This discussion thread is closed

Replies have been disabled for this discussion.