我尝试了这样一段代码来遍历u64
:
let mut message: u64 = 0x1234123412341234;
let msg = &message as *mut u8;
for b in 0..8 {
// ...some work...
}
不幸的是,Rust不允许这种类似C的索引。
答案 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);
}
}
答案 1 :(得分:3)
将u64
转换为数组[u8; 8]
是安全的:
let message_arr: [u8; 8] = unsafe { mem::transmute(message) };
for b in &message_arr {
println!("{}", b)
}
在行动on the playground中查看此内容。