在 Rust 中循环遍历整数字节的惯用方法是什么?
What is the idiomatic way of looping through the bytes of an integer number in Rust?
我试过这样一段代码循环遍历一个u64
:
的字节
let mut message: u64 = 0x1234123412341234;
let msg = &message as *mut u8;
for b in 0..8 {
// ...some work...
}
不幸的是,Rust 不允许这种类似 C 的索引。
将 u64
转换为数组是安全的 [u8; 8]
:
let message_arr: [u8; 8] = unsafe { mem::transmute(message) };
for b in &message_arr {
println!("{}", b)
}
查看实际效果 on the playground。
虽然 transmute
-ing 是可能的(), it is better to use 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);
}
}
我试过这样一段代码循环遍历一个u64
:
let mut message: u64 = 0x1234123412341234;
let msg = &message as *mut u8;
for b in 0..8 {
// ...some work...
}
不幸的是,Rust 不允许这种类似 C 的索引。
将 u64
转换为数组是安全的 [u8; 8]
:
let message_arr: [u8; 8] = unsafe { mem::transmute(message) };
for b in &message_arr {
println!("{}", b)
}
查看实际效果 on the playground。
虽然 transmute
-ing 是可能的(
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);
}
}