Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

แปลง Endianness (Big/Little Endian) ใน C++

Endianness: ลำดับเก็บ byte ในหน่วยความจำ

  • Big-endian: MSB (most significant byte) อยู่ address ต่ำสุด
  • Little-endian: LSB อยู่ address ต่ำสุด (x86, ARM ทั่วไป)

ตัวอย่าง 32-bit value 0x98765432 (สมมติ 4 bytes):

  • Big-endian: 98 76 54 32
  • Little-endian: 32 54 76 98

ฟังก์ชันสลับ Byte Order (32-bit)

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

โค้ดทดสอบ

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

หมายเหตุ

  • C++23 มี std::byteswap ใน <bit>
  • Network byte order = Big-endian ใช้ htonl/ntohl (POSIX)
  • ตรวจสอบ endianness runtime: union { uint32_t i; char c[4]; } u = {1}; bool little = u.c[0];