-
Notifications
You must be signed in to change notification settings - Fork 194
Description
Motivated by the question from @vmagnin at Discourse. For those not familiar with the term endianness (quoting the D language documentation):
Endianness refers to the order in which multibyte types are stored. The two main orders are big endian and little endian. The compiler predefines the version identifier BigEndian or LittleEndian depending on the order of the target system. The x86 systems are all little endian.
The times when endianness matters are:
- When reading data from an external source (like a file) written in a different endian format.
- When reading or writing individual bytes of a multibyte type like longs or doubles.
Another place where endianness matters is in network stacks and communication protocols. All of the protocol layers in the Transmission Control Protocol and the Internet Protocol (TCP/IP) suite are defined to be big-endian.
Would there be any interest to provide procedures to detect platform endianness at run-time?
In C this can be done with the following program (taken from the IBM Developer guide Writing endian-independent code in C):
#define LITTLE_ENDIAN 0 #define BIG_ENDIAN 1 int endian() { int i = 1; char ∗p = (char ∗)&i; if (p[0] == 1) return LITTLE_ENDIAN; else return BIG_ENDIAN; }
Alternative solution in C - 1
C99 solution taken from here: https://stackoverflow.com/questions/1001307/detecting-endianness-programmatically-in-a-c-program
bool is_big_endian(void) { union { uint32_t i; char c[4]; } bint = {0x01020304}; return bint.c[0] == 1; }
A solution using deprecated Fortran features is given here:
subroutine endian(litend) c checks if this is a little endian machine c returns litend=.true. if it is, litend=.false. if not integer*1 j(2) integer*2 i equivalence (i,j) logical litend i = 1 if (j(1).eq.1) then litend = .true. else litend = .false. end if end
A modern Fortran equivalent could be something like:
pure logical function little_endian() integer(int8) :: j(2) integer(int16) :: i i = 1 j = transfer(source=i,mold=j,size=2) if (j(1) == 1) then little_endian = .true. else little_endian = .false. end if end function
Such procedures are very likely already part of some (legacy) Fortran libraries.
They are also available in other languages:
- D: std.system.Endian/endian
- C++ (since C++20):
std::endian
Some related procedures for byte swapping could also be useful. Julia has bswap
. Equivalent C versions of this function are given at the bottom of this link.
Issues:
- Not clear how to handle the PDP-11 😉