将大端转换为中小端

convert big endian to mid little endian

我在 C 中有以下 big endian:

int32_t num = 0x01234567;

我想像这样将其转换为中小端:0x45670123

我如何使用按位运算符在 C 中执行此操作

一个非常简单的方法是:

  • 使用 AND 运算符从 num 中读取一个字节。
  • 将读取的字节移动到输出数字中您想要的位置。
  • OR 移位后的字节与您的输出编号。
  • 重复直到完成。

示例:

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.