Chris said:
I would like to swap (change order) for a byte (e.g)
02 in Hex => 02 in Dec => 0000.0010 in Binary
Need to swap the bits as:
40 in Hex => 64 in Dec => 0100.0000 in Binary
What is the easiet way?
For swap integer (short) I use htonl (htons).
Thank you
Chris
If you have a 64 bit machine with 64 bit integer support
and you need to swap lotsa bits in bytes, this algorithm will swap 8
bytes at a time in around 20 instructions.
typedef unsigned long long swap_t;
inline swap_t swapbitsinbytes( swap_t v )
{
const swap_t h_mask_1 = 0xaaaaaaaaaaaaaaaaLL;
const swap_t l_mask_1 = 0x5555555555555555LL;
const swap_t h_mask_2 = 0xccccccccccccccccLL;
const swap_t l_mask_2 = 0x3333333333333333LL;
const swap_t h_mask_4 = 0xf0f0f0f0f0f0f0f0LL;
const swap_t l_mask_4 = 0x0f0f0f0f0f0f0f0fLL;
v = ( ( v & h_mask_1 ) >> 1 ) | ( ( v & l_mask_1 ) << 1 );
v = ( ( v & h_mask_2 ) >> 2 ) | ( ( v & l_mask_2 ) << 2 );
return ( ( v & h_mask_4 ) >> 4 ) | ( ( v & l_mask_4 ) << 4 );
}
#include <iostream>
int main()
{
std::cout << std::hex << swapbitsinbytes( 0x0102040810204080LL );
}