英文:
In bitvec, how does storage size affect loading?
问题
How does the storage size affect how load
ing works?.
当存储大小设置为 usize
时,load
方法返回预期的 1027。当设置为 u8
时,我似乎找不到打印的数字与位模式之间的关系,
当存储大小设置为 usize
时,load
方法返回预期的 1027。当设置为 u8
时,我似乎找不到打印的数字与位模式之间的关系,
当存储大小设置为 usize
时,load
方法返回预期的 1027。当设置为 u8
时,我似乎找不到打印的数字与位模式之间的关系,
英文:
How does the storage size affect how load
ing works?.
As an example, in the below snippet, a 22 bit vector is separated into two groups of 11 bits. Each of these groups has the same pattern, storing the decimal number 1027.
let vec22 = bitvec![u8 /* usize */, Msb0; 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, /* next */ 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1]; // 1027, 1027
let chunks = vec22.chunks(11);
let numbers = chunks
.into_iter()
.map(|chunk| {
let number: usize = chunk.load();
println!("{} {}", chunk, number);
number
})
.collect::<Vec<_>>();
When the storage size is usize
, the load
method returns the expected 1027. When set to u8
, I can't seem to find a relationship between the printed numbers and the bit patterns,
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1] 896 // expected 1027
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1] 112 // expected 1027
How does changing the storage size affect these numbers?
答案1
得分: 0
以下是翻译好的部分:
- 所有计算机都同意数组中较早的元素具有较低的地址(即“首先出现”),但元素内的字节可以以任何顺序排列。
- 在
bitvec
中,T
用于描述存储位的底层元素类型(u8、i16、u32、usize 等)。 - 当加载跨越多个
T
元素的位模式到新变量中时,需要明确告诉bitvec
如何解释跨越T
的位的重要性。如果较早的T
更重要,请使用load_be
。如果较早的T
较不重要,请使用load_le
。 load
函数应用与其运行的机器体系结构相匹配的*be
或*le
加载器,因此不具备可移植性,而且可能与位模式的设置方式不匹配。
最后,回答 OP 的问题,为什么在 u8
和 usize
之间切换会产生不同的结果:因为使用 u8
导致 11 位块跨越了2个字节,因此使得 bitvec
选择如何解释这些字节上的位的相对重要性。恰好,load
使用运行在其上的机器的字节顺序,与定义 vec22
的预期字节顺序不匹配。
英文:
There is some fundamental knowledge on endianess and bitvec
that's necessary to be able to answer the question,
- All computers agree that earlier elements in an array have lower addresses (i.e., "come first"), but bytes within the elements may be arranged in any order
- In
bitvec
,T
is used to describe the underlying element type storing the bits (u8, i16, u32, usize, etc). - When loading a bit pattern that spans over multiple
T
elements into a new variable,bitvec
needs to be explicitly told how to interpret the significance of bits acrossT
s. If earlierT
s are more significant, useload_be
. If earlierT
s are less significant, useload_le
. - The
load
function applies either the*be
or*le
loader that matches the arch of the machine it's running on, thus not portable, and which may or may not match how the bit patters have been set up.
Finally, to answer OP question as to why switching between u8
and usize
was producing different results: because uisng u8
caused the 11-bit chunk to be spread across 2 bytes, thus making bitvec
choose how to interpret the relative significance of the bits across those bytes. It just so happens that load
, which uses the endianness of the machine it's running on, didn't match the intended endianness with which vec22
is defined.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论