endiantest

A test for endian-ness. Initially used in service of a different project but was made into its own repo
Log | Files | Refs | README | LICENSE

endiantest.c (1975B)


      1 /*
      2   Test for endian-ness
      3   "endiantest.c"
      4   M. Yamanaka
      5   email: myamanaka@live.com
      6   website: csmyamanaka.com
      7   license: MIT (See included "LICENSE" file for details)
      8 */
      9 
     10 #include <stdio.h>
     11 
     12 int main(){
     13   /*
     14     Originally, this test was used as a test for my other project "File IO ++" (fileiopp)
     15     because it was quite necessary that I know the endian-ness of my compiler.
     16     I figured it could be useful in itself to the point that it merits its own repo.
     17   */
     18 
     19   /*
     20     I'm pretty sure integers are 4 bytes long at least on the compiler that I'm using.
     21     Integer 65 could be stored as 00 00 00 65 or 65 00 00 00 (btw I chose 65 because it's the letter 'A' as a char).
     22     I'm not bothering with the whole signed vs unsigned because it should be irrelevant given how small the number is
     23     and also given that it's a positive number so there is no issue with any of the two's complement stuff.
     24   */
     25   int n = 65;
     26   
     27   /*
     28     Having a char pointer point to the "first byte" of the integer could either mean
     29     that it's pointing to "00" or to "65".
     30   
     31     For big-endian, the most significant byte is stored in the first byte (i.e. how normal humans read)
     32     The reverse is true for little endian.
     33 
     34     Using a char pointer (which has a stride length of 1 byte) it should be fairly trivial to read the byte at the address of integer n
     35     and the three following bytes (reading any more than that would probably cause a seg fault).
     36 
     37     The following table should serve as a tl;dr
     38 
     39     byte  | 00 | 01 | 02 | 03 |
     40     ------+----+----+----+----+
     41           | 00 | 00 | 00 | 65 | big endian
     42     int n +----+----+----+----+
     43           | 65 | 00 | 00 | 00 | little endian
     44     ------+----+----+----+----+
     45     char* | +0 | +1 | +2 | +3 |
     46 
     47   */
     48   char* pcn = (char*)&n;
     49 
     50   if(*pcn == '\0' && *(pcn + 3) == 'A') printf("big endian\n");
     51   else if(*pcn == 'A' && *(pcn + 3) == '\0') printf("little endian\n");
     52   else printf("something probably went wrong\n");
     53   return 0;
     54 }

Generated using stagit (https://codemadness.org/stagit.html)