I want to exchange the bytes of a number. Example the binary representation of a number is
00000001 00011000 00000100 00001110
. I want to reverse it: 00001110 00000100 00011000 00000001
.
Can you please help? The current code is below:
void showBits(int n)
{
int i,k,andMask;
for(i=15;i>=0;i--)
{
开发者_Go百科 andMask=1<<i;
k=n&andMask;
k==0?(cout<<"0"):(cout<<"1");
}
}
int reverse(int a)
{
int b=a<<8;
int c=a>>8;
return (b|c);
}
int main()
{
int a=10;
showBits(a);
int b=reverse(a);
showBits(b);
cin.get();
}
Something like this should work:
result = ((number & 0xFF) << 24) | ((number & 0xFF00) << 8) |
((number & 0xFF0000) >> 8) | ((number & 0xFF000000) >> 24);
int myInt = 0x012345678
__asm {
mov eax, myInt
bswap eax
mov myInt, eax
}
If you want to simply reverse a 32-bit number, you can use a bit-shifting technique that isolates each byte region using bit-masks and logical AND
, and then swaps those bytes by the appropriate number of shifted bits using the bit-shift operators >>
and <<
. You can then recombined the bits using logical OR
like so:
int temp = 0x12345678;
temp = ((0xFF & temp) << 24) | ((0xFF00 & temp) << 8) | ((0xFF0000 & temp) >> 8) |
((0xFF000000 & temp) >> 24));
You'll now end up with a final value in temp
of 0x78563412
.
Update: Okay, I'm looking over you code, and noting the following:
- The size of
int
it seems like you're wanting to work with from the binary digit you have posted is 32-bits ... so yourshowBits
function is not cycling through enough bits to display an entire 32-bit integer. As far as I can see right now, it will only show up to the 16 lower bits. So you'll need to be clear on whether you're working on a platform that definesint
as 16 or 32-bits. - Your
reverse
functions is not correct. If you have a 32-bitint
like0x12345678
, and you shift it left by 8-bits, you will end up with0x34567800
. Likewise, when you shift it right by 8-bits, you will just end up with0x00123456
. Shifting a number does not rotate the values through their respective positions (i.e., a shift left of 8-bits would not give you0x34567812
). Plus, even if it did, the logicalOR
of the rotated values would still not be a correct reversal of the values. Instead, you must use the technique described above that uses bit-masks and logicalAND
to isolate each byte, and then shift those bits the appropriate number of places in order to reverse the bits in a 32-bit word.
If your original task to to convert from machine-specific byte order to big endian and back, take a look at the hton* and ntoh* functions.
http://minix1.woodhull.com/manpages/man3/hton.3.html
精彩评论