Comment

Comment by EdSchouten

In my opinion bugs related to endianness expose a design flaw in the C/C++ programming languages, or at least in the way people tend to use those languages. It isn't that hard to write code that works well with any kind of endianness, and you don't need stuff like __BYTE_ORDER__ for that. For example, if I wanted to read a little endian 32-bit integer value from a byte stream, I could write a function like this:

    uint32_t read_int32(unsigned char *b) {
        return uint32_t(b[0]) |
               (uint32_t(b[1]) << 8) |
               (uint32_t(b[2]) << 16) |
               (uint32_t(b[3]) << 24);
    }
Which, according to Godbolt.org, at -O2 or higher compiles to:

    read_int32(unsigned char*):
        mov     eax, DWORD PTR [rdi]
        ret
No magic needed!
parent EdSchouten 5 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton