[英]Why does std::bitset expose bits in little-endian fashion?
When I use std::bitset<N>::bitset( unsigned long long )
this constructs a bitset and when I access it via the operator[]
, the bits seems to be ordered in the little-endian fashion. 当我使用std::bitset<N>::bitset( unsigned long long )
这会构造一个位集,而当我通过operator[]
访问它时,这些位似乎是按照小端顺序排列的。 Example: 例:
std::bitset<4> b(3ULL);
std::cout << b[0] << b[1] << b[2] << b[3];
prints 1100
instead of 0011
ie the ending (or LSB) is at the little (lower) address, index 0. 打印1100
而不是0011
即结尾(或LSB)在小(低)地址索引0处。
Looking up the standard, it says 查找标准,它说
initializing the first M bit positions to the corresponding bit values in
val
将前M个位位置初始化为val
的相应位值
Programmers naturally think of binary digits from LSB to MSB (right to left). 程序员自然会想到从LSB到MSB(从右到左)的二进制数字。 So the first M bit positions is understandably LSB → MSB, so bit 0 would be at b[0]
. 因此, 前M个位的位置可以理解为LSB→MSB,因此位0将位于b[0]
。
However, under shifting, the definition goes 但是,在转移的情况下,定义
The value of
E1
<<E2
isE1
left-shiftedE2
bit positions;E1
<<E2
的值是E1
左移E2
位的位置; vacated bits are zero-filled. 空出的位为零。
Here one has to interpret the bits in E1
as going from MSB → LSB and then left-shift E2
times. 在这里,必须将E1
的位解释为从MSB→LSB开始,然后左移E2
次。 Had it been written from LSB → MSB, then only right-shifting E2
times would give the same result. 如果它是从LSB→MSB写入的,则只有右移E2
次才能得到相同的结果。
I'm surprised that everywhere else in C++, the language seems to project the natural (English; left-to-right) writing order (when doing bitwise operations like shifting, etc.). 令我惊讶的是,在C ++的其他所有地方,该语言似乎都投射出自然的(英语;从左到右)书写顺序(进行移位之类的按位操作时)。 Why be different here? 为什么在这里与众不同?
There is no notion of endian-ness as far as the standard is concerned. 就标准而言,没有字节顺序的概念。 When it comes to std::bitset
, [template.bitset]/3
defines bit position : 关于std::bitset
, [template.bitset]/3
定义位位置 :
When converting between an object of class
bitset<N>
and a value of some integral type, bit positionpos
corresponds to the bit value1<<pos
. 在bitset<N>
类的对象和某个整数类型的值之间进行转换时, 位位置pos
对应于位值1<<pos
。 The integral value corresponding to two or more bits is the sum of their bit values. 对应于两个或多个位的整数值是它们的位值之和。
Using this definition of bit position in your standard quote 在标准报价中使用此位位置定义
initializing the first
M
bit positions to the corresponding bit values inval
将前M
位位置初始化为val
的相应位值
a val
with binary representation 11
leads to a bitset<N> b
with b[0] = 1
, b[1] = 1
and remaining bits set to 0
. 一个val
用二进制表示11
通向bitset<N> b
与b[0] = 1
, b[1] = 1
,并设置为剩余位0
。
这与位通常被编号的方式是一致的-位0代表2 0 ,位1代表2 1 ,依此类推。这与体系结构的字节序无关,后者涉及字节顺序而不是位顺序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.