问题
Given these bytes (hexadecimal representation):
0F
1A
2C
how can I get:
F0
A1
C2
?
回答1:
Use bitwise operators.
((x & 0x0f) << 4) | ((x & 0xf0) >> 4)
回答2:
You can do it like this:
((x & 0x0f) << 4 ) | ((( x & 0xf0) >> 4) & 0xf )
This looks a lot like Josh Kelley's answer, but Josh's answer is wrong. Here's why:
#include <stdio.h>
int main( int argc, char *argv[] )
{
signed char x = 0x80;
x >>= 4;
printf( "%x\n", x );
}
Gives output:
0xfffffff8
Because the >>
operator preserves the sign bit of the shifted operand. I.e., a 1 in the most significant bit will be propagated leftward to preserve the sign of the value.
来源:https://stackoverflow.com/questions/37998810/how-to-swap-byte-nibbles