在Rust中循环遍历整数的字节的惯用方法是什么?

时间:2018-05-27 11:24:08

标签: arrays rust iteration byte unsafe

我尝试了这样一段代码来遍历u64

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

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

不幸的是,Rust不允许这种类似C的索引。

2 个答案:

答案 0 :(得分:5)

尽管可以transmute - see @Tim's answer),但最好使用the byteorder crate来保证字节顺序:

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

答案 1 :(得分:3)

u64转换为数组[u8; 8]是安全的:

let message_arr: [u8; 8] = unsafe { mem::transmute(message) };
for b in &message_arr {
    println!("{}", b)
}

在行动on the playground中查看此内容。