cs205-lecture-examples

Example codes used during Harvard CS205 lectures
git clone https://git.0xfab.ch/cs205-lecture-examples.git
Log | Files | Refs | README | LICENSE

endianness.cpp (1289B)


      1 #include <iomanip>
      2 #include <iostream>
      3 #include <string>
      4 
      5 int main(void)
      6 {
      7     // clang-format off
      8 
      9                  // Little endian byte order: (e.g Intel, AMD)
     10                  //
     11                  //    high address
     12                  //    |
     13                  //    |     low address
     14                  //    |     |
     15     int one = 1; // 0x00000001
     16                  //   ||    ||
     17                  //   ||    least significant byte
     18                  //   ||
     19                  //   most significant byte
     20 
     21                  // Big endian byte order: (e.g. IBM)
     22                  //
     23                  //    high address
     24                  //    |
     25                  //    |     low address
     26                  //    |     |
     27                  // 0x01000000
     28                  //   ||    ||
     29                  //   ||    least significant byte
     30                  //   ||
     31                  //   most significant byte
     32 
     33     // clang-format on
     34 
     35     // create a pointer to the low address byte
     36     char *low_address = (char *)&one;
     37 
     38     // print its value
     39     const std::string endianness = (*low_address) ? "little" : "big";
     40     std::cout << "Low address byte = 0x" << std::hex << std::setfill('0')
     41               << std::setw(2) << (int)(*low_address) << " (" << endianness
     42               << " endian)\n";
     43     return 0;
     44 }