DEV Community

Noppadol Anuroje
Noppadol Anuroje

Posted on

วิธีตรวจสอบระบบว่าเป็น Little Endian หรือ Big Endian

#include <iostream>
#include <bitset>

int main() {
  unsigned int i = 1;
  char *c = (char*)&i;
  if (*c)
      std::cout << "Little endian" << std::endl;
  else
      std::cout << "Big endian" << std::endl;

  return 0;
}

จาก source code ด้านบน การประกาศตัวแปร i = 1 ถ้าเป็น Little endian เราจะได้รูปแบบการจัดเก็บในหน่วยความจำดังนี้

สมมติว่าระบบเราเป็น 32bit ดังนั้น รูปแบบภายในหน่วยความจำที่จัดเก็บของ i จะเป็นดังนี้

Little endian
Higher Byte--> Lower Byte
|0x01|0x00|0x00|0x00|

Big endian
Higher Byte--->Lower Byte
|0x00|0x00|0x00|0x01|

จาก source code
char c = (char*)&i;
*c จะชี้ไปที่ตำแหน่งแรกของหน่วยความจำ คือ ตำแหน่ง bit ซ้ายสุด หรือตำแหน่ง high
ดังนั้น ถ้าเป็น Little endian จะแสดงผลเป็น Little endian แต่ถ้าเป็น Big endian จะแสดงผลเป็น Big endian

Top comments (0)