To determine the endianness of a system, I plan to store a multi-byte integer value in a variable and access the first byte via an unsigned char wrapped in a union; for example:
union{
unsigned int val;
unsigned char first_byte;
} test;
test.val = 1; /* stored in little-endian system as "0x01 0x00 0x00 0x00" */
if(test.first_byte == 1){
printf("Little-endian system!");
}else{
printf("Big-endian system!");
}
I want to make this test portable across platforms, but I’m not sure if the C99 standard guarantees that the unsigned int data type will be greater than one byte in size. Furthermore, since a “C byte” does not technically have to be 8-bits in size, I cannot use exact width integer types (e.g. uint8_t, uint16_t, etc.).
Are there any C data types guaranteed by the C99 standard to be at least two bytes in size?
P.S. Assuming an unsigned int is in fact greater than one byte, would my union behave as I’m expecting (with the variable first_byte accessing the first byte in variable val) across all C99 compatible platforms?
Since
intmust have a range of at least 16 bits,intwill meet your criterion on most practical systems. So wouldshort(andlong, andlong long). If you want exactly 16 bits, you have to look to see whetherint16_tanduint16_tare declared in<stdint.h>.If you are worried about systems where
CHAR_BITis greater than 8, then you have to work harder. IfCHAR_BITis 32, then onlylong longis guaranteed to hold two characters.What the C standard says about sizes of integer types
In a comment, Richard J Ross III says:
On the contrary, the C standard has specifications on the lower bounds on the ranges that must be supported by different types, and a system with 10-bit
intwould not be conformant C.Specifically, in ISO/IEC 9899:2011 §5.2.4.2.1 Sizes of integer types
<limits.h>, it says: