将大字节序转换为小字节序

时间:2020-05-16 02:28:21

标签: c bitwise-operators bit bit-shift

我在C语言中具有以下大字节序:

int32_t num = 0x01234567;

我想将其转换为0x45670123

如何在C语言中使用按位运算符

1 个答案:

答案 0 :(得分:1)

一种非常简单的方法是:

  • 使用AND运算符从num中读取一个字节。
  • 将读取的字节移至输出编号中所需的位置。
  • 将移位后的字节与您的输出编号相乘。
  • 重复直到完成。

示例:

uint32_t num = 0x01234567;
uint32_t output = 0;

uint32_t firstByte = num & 0xff000000; // firstByte is now 0x01000000
// Where do we want to have 0x01 in the output number?
// 0x45670123
//       ^^ here
// Where is 0x01 currently?
// 0x01000000
//   ^^ here
// So to go from 0x01000000 to 0x00000100 we need to right shift the byte by 16 (4 positions * 4 bits)
uint32_t adjByte = firstByte >> 16; // adjByte is now 0x0100
// OR with output
output |= adjByte;

AND, Shift & OR operator on wikipedia.