Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Chuyển đổi Endianness (Big-endian ↔ Little-endian) trong C++


Big-endian: byte high-order trước. Little-endian: byte low-order trước. Ví dụ 0x9876543210:

  • Big: 98 76 54 32 10
  • Little: 10 32 54 76 98

Hoán đổi 32-bit (macro)

#define SWAP32(x) (((x)>>24) | (((x)&0x00FF0000)>>8) | (((x)&0x0000FF00)<<8) | ((x)<<24))

Ví dụ đầy đủ

#include <iostream>, <cstdio>
#define SWAP32(x) ...

void print_hex(const char* p, int n) {
    for (int i=0;i