Platform endianness check

How do I check the endianness of the platform in rust?

Thanks in advance.

TLDR is cfg(target_endian), but so far as I know all supported platforms are little-endian anyway.

FWIW, you should in general just be able to use the various integer methods like {from,to}_{be,le,ne}{,_bytes}

2 Likes

Sigh. No. If you look on list of supported platforms then you'll find both mips-unknown-linux-gnu and powerpc-unknown-linux-gnu in there.

And these are not exactly rare or exotic: many cheap routers use MIPS precisely because these are big endian and thus more efficient if the only thing you need to do it to process TCP/IP packets.

And you can test that code with miri's --target option without purchasing such router, too.

5 Likes

IBM mainframe s390x-unknown-linux-gnu is big endian too, and supported at tier 2 in Rust.

2 Likes

I stand corrected! I checked what endianness was actually available out there a while ago and got a lot of "some obscure and no longer in production super-computers, and since weird Chinese panels that used the big endian mode of ARM for some reason". Don't know how I missed MIPS being in use still.

One can use the cfg macro in conjunction with target_endian like this :

fn main(){
    if cfg!(target_endian = "big") {
        println!("This is a BigEndian system.")
    } else {
        println!("This is a LittleEndian system.")
    }

    if cfg!(target_endian = "little") {
        println!("This is a LittleEndian system.")
    } else {
        println!("This is a BigEndian system.")
    }
}

full disclosure, I tested this code on my system which is a LittleEndian system and that works, but it would be nice if someone can confirm this on a BigEndian system :slight_smile:

Your run-time endianness identifying function can be collapsed to just

const fn is_target_little_endian() -> bool {
    u16::from_ne_bytes([1, 0]) == 1
}
3 Likes

Why not just:

fn main() {
    #[cfg(target_endian = "big")]
    println!("This is a BigEndian system.");
    #[cfg(target_endian = "little")]
    println!("This is a LittleEndian system.");
}

Much simpler logic IMO.

cargo +nightly miri run --target powerpc-unknown-linux-gnu to test it.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.