How to swap byte nibbles? [duplicate]

痴心易碎 提交于 2019-12-13 08:45:39

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!