Re: byte order



On Jan 8, 9:37 pm, Raymond Wiker <r...@xxxxxxxxxxxx> wrote:
Not in Common Lisp.

Not in standard C either.

You're joking, right?

// returns 1 if little endian, 0 if big
int am_i_little_endian() {
    int x = 0x12345678;
    char* b = (char*)&x;
    return *b == (x & 0xFF);
}

        Are you *absolutely* sure that's standard C, and not just
something that happens to work most of the time?

§6.2.6.1.4 of ISO/IEC 9899:1999 provides explicit provisions for
casting objects to arrays of bytes, and guarantees that such an array
will actually correspond to the in-memory representation.

The standard also gives the possibility of integer types containing
padding bits, and it is not specified how such bits can be detected.
It is, however, specified that value bits must be continuous, and that
char is the smallest integer type. Therefore, assuming 8-bit bits, the
above code is bound to be portable and reliably detect little-
endianness[1] of the host machine.

Cheers,
Maciej

[1] Little-endianness understood as "least significant value byte
comes first". An implementation using little-endian value
representation with padding bits coming before the value bits wouldn't
be reliably detected, but then, any such padding-using implementation
would need to be treated as another type of endianness anyway by any
code that cares about endianness, so it's not really an issue.
.



Relevant Pages

  • Re: byte order
    ... casting objects to arrays of bytes, and guarantees that such an array ... The standard also gives the possibility of integer types containing ... padding bits, and it is not specified how such bits can be detected. ... Bound variables, free programmers. ...
    (comp.lang.lisp)
  • Re: Four or Two Bytes?
    ... Not on the DS9K. ... unsigned short can have INT_MAX padding bytes on the DS9K. ... For unsigned integer types other than unsigned char, ... the bits of the object representation shall be divided into ...
    (comp.lang.c)
  • Re: Code speedup
    ... >>Your intuition can often be wrong... ... > statically-sized arrays to be allocated adjacently, ... Cache-tag addresses for Aare ... padding the J-dimension of A may change this behavior ...
    (comp.lang.fortran)
  • Re: POSIX and 8-bit bytes
    ... >> N, no padding bits, and a two’s complement representation. ... The section heading "Exact-width integer types" has certain ... >> I don't know of a single hosted implementation for any DSP, ... Porting network stacks is likely, ...
    (comp.lang.c)
  • Re: Differences between pointers
    ... >> rlb@xxxxxxxxxxxxxxxxxxxxxx (Richard Bos) writes: ... >>> must contain padding bits, ... >> sanity.] ... on any other types besides integer types. ...
    (comp.lang.c)