我正在重建u128通过互联网传递的数字。我的想法是u8在连接的一端将数字分解为s,发送这些并u128在另一端重建。
我尝试u8通过将其指针转换*const u8为to来重建缓冲区*const u128:
fn main() {
let mut b = [0u8; 16];
b[14] = 1;
let addr = &b as *const u8 as *const u128;
unsafe {
println!("{:?}", &b as *const u8);
println!("{:?}\n", b);
println!("{:?}", addr);
println!("n = {}", *addr);
}
}
Run Code Online (Sandbox Code Playgroud)
令我惊讶的是,生成的输出如下所示:
0x7efe2088
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]
0x7efe2088
n = 5192296858534827628530496329220096
Run Code Online (Sandbox Code Playgroud)
我希望这个数组包含
00000000 00000000 ... 00000001 00000000 = 256
Run Code Online (Sandbox Code Playgroud)
现在我很困惑。考虑两种不同的选择:
b[14]作为第二个字节存储;*const u128(指向b[0])向后读取分配的字节。其中哪一项是正确的?关于 Rust(或一般的计算机)存储数据的方式,我有什么不明白的地方吗?
Your confusion stems from endianness. This concept applies to computers in general, not just Rust. Some computer architectures are natively big-endian (e.g. MIPS), some are little endian (e.g. x86), and some can be both (e.g. ARM)!.
为了通过互联网传输数字,您应该选择发送它们的顺序(大端或小端;大端是传统选择,尽管小端系统现在更常见),然后显式转换发送和接收时。这样,即使两台计算机的字节序不同(例如,MIPS 和 x86-64 不同),您的程序仍然可以运行。
正如@loganfsmyth 指出的那样,Rust 有内置方法来进行从 au128到u8s数组的转换(反之亦然),这些方法是:
| 归档时间: |
|
| 查看次数: |
178 次 |
| 最近记录: |