Hacker News new | ask | show | jobs
by josephg 66 days ago
Nah, that's a terrible way to handle endian-ness. Your "big endian" types infect your entire program. And you pay a cost with every computation you do with them.

Just treat the data on disk / on the wire as if it were in some encoded format. Parse on load. Encode back out to the expected format when you save it. Within your program, just use your language's native int formats.

For example, in C I use something like this:

    uint32_t read_be_u32(uint8_t data[4]) {
        return ((uint32_t)data[0] << 24) |
            ((uint32_t)data[1] << 16) |
            ((uint32_t)data[2] << 8)  |
            ((uint32_t)data[3]);
    }
... And the equivalent for little endian data. Modern optimizers will happily turn that into the right instructions - either a noop or bswap - as appropriate depending on the target architecture.

You can do the same thing in Rust, Go, or any other language. No special type definitions or macros necessary.

https://godbolt.org/z/746EaYx4r