Search code examples
arraysrustiterationbyteunsafe

What is the idiomatic way of looping through the bytes of an integer number in Rust?


I tried such a piece of code to loop through the bytes of a u64:

let mut message: u64 = 0x1234123412341234;
let msg = &message as *mut u8;

for b in 0..8 {
    // ...some work...
}

Unfortunately, Rust doesn't allow such C-like indexing.


Solution

  • While transmute-ing is possible (see @Tim's answer), it is better to use the byteorder crate to guarantee endianness:

    extern crate byteorder;
    
    use byteorder::ByteOrder;
    
    fn main() {
        let message = 0x1234123412341234u64;
        let mut buf = [0; 8];
        byteorder::LittleEndian::write_u64(&mut buf, message);
    
        for b in &buf {
             // 34, 12, 34, 12, 34, 12, 34, 12, 
             print!("{:X}, ", b);
        }
    
        println!("");
    
        byteorder::BigEndian::write_u64(&mut buf, message);
    
        for b in &buf {
             // 12, 34, 12, 34, 12, 34, 12, 34, 
             print!("{:X}, ", b);
        }
    }
    

    (Permalink to the playground)