#How robust is this method for detecting machine endianness?

13 messages · Page 1 of 1 (latest)

south fossil
#

I have the following function to detect machine endianness:

fn endianness() -> Endianness {
    let x = 0x10u16;
    let bytes: [u8; 2] = unsafe { std::mem::transmute(x) };
    match bytes {
        [1, 0] => Endianness::Big,
        [0, 1] => Endianness::Little
    }
}

enum Endianness {
    Little,
    Big
}

Does this have any caveats I should be aware of?

old cosmos
dim flare
#

Yeah, if your code is only worried about the target's endianness, use:```rust
#[cfg(target_endian = "big")]
{
/* Value to calculate or stuff to do on big-endian targets /
}
#[cfg(target_endian = "little")]
{
/
Value to calculate or stuff to do on little-endian targets */
}

#

If you're going to be dealing with endianness beyond the target's:

#

?play ```rust
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[repr(u8)]
pub enum Endianness {
Big,
Little,
}

pub const TARGET_ENDIANNESS: Endianness = {
#[cfg(target_endian = "big")]
{
Endianness::Big
}
#[cfg(target_endian = "little")]
{
Endianness::Little
}
};

#[inline(always)]
pub fn target_endianness() -> Endianness {
TARGET_ENDIANNESS
}

fn main() {
dbg!(target_endianness());
}

pliant epochBOT
#
[src/main.rs:25] target_endianness() = Little```
dim flare
#

Like if you're going to talk about the endianness of file format fields or something.

#

Also, remember that to_be_bytes or from_be_bytes (and le versions) exist for things that might differ from the target endianness.

worn bough
dim flare
#

It was mainly to show the option that you can use a constant.

#

I'm not sure how they'd like to structure it.

dreamy girder
#

just in case someone chooses to compile for a middle-endian target, you wouldn’t want your code to be incorrect