为什么的std :: bitset的Little Endian的方式暴露位? [英] Why does std::bitset expose bits in little-endian fashion?
问题描述
当我使用和std :: bitset< N> ::位集(无符号很长很长)
此构造一个bitset,当我通过运算符[]
中,位似在小端的方式进行订购。例如:
和std :: bitset 4;> B(3ULL);
性病::法院LT&;< B [0]&下;&下; B〔1];&下; B〔2〕&下;&下; B〔3〕;
打印 1100
而不是 0011
即结束(或LSB)是小(低)地址,指数0。
仰望的标准,它说:
在初始化
的前M位的位置到相应的位值VAL
块引用>程序员自然会想到从LSB到MSB(从右到左)二进制数字。所以的前M位的位置的是可以理解LSB→MSB,因此位0会在
B [0]
。不过,根据移位,定义云
E1
1所述的价值;<E2
是E1
左移E2
位的位置;腾空位零填充。
块引用>在这里,人们不得不间preT位在
写E1
从MSB去→LSB,然后左移E2
倍。如果这是从LSB→MSB,则仅右移E2
次将给予同样的结果。我很惊讶,在C ++其他地方,语言似乎投射自然(英语;左到右)书写顺序(做这样移位运算的时候,等)。为什么会有所不同吗?
解决方案有是尽可能的标准而言没有字节序的概念。当谈到
和std :: bitset
,[template.bitset] / 3
定义的位的位置
当类的对象之间进行转换
位集< N>
和值
一些整数类型,位的位置的POS
对应位值1<< POS
。
对应于两个或更多个比特的积分值是所述总和
他们的位值。
块引用>使用的的这个定义位的位置的在标准报价
初始化第一个
M
的位的位置的在VAL
<相应的位值/ p>
块引用>在
VAL
二进制重新presentation11
导致位集&LT; N'GT; b
与B [0] = 1
,B [1] = 1
和剩余设置为0
位。When I use
std::bitset<N>::bitset( unsigned long long )
this constructs a bitset and when I access it via theoperator[]
, the bits seems to be ordered in the little-endian fashion. Example:std::bitset<4> b(3ULL); std::cout << b[0] << b[1] << b[2] << b[3];
prints
1100
instead of0011
i.e. the ending (or LSB) is at the little (lower) address, index 0.Looking up the standard, it says
initializing the first M bit positions to the corresponding bit values in
val
Programmers naturally think of binary digits from LSB to MSB (right to left). So the first M bit positions is understandably LSB → MSB, so bit 0 would be at
b[0]
.However, under shifting, the definition goes
The value of
E1
<<E2
isE1
left-shiftedE2
bit positions; vacated bits are zero-filled.Here one has to interpret the bits in
E1
as going from MSB → LSB and then left-shiftE2
times. Had it been written from LSB → MSB, then only right-shiftingE2
times would give the same result.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.). 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:When converting between an object of class
bitset<N>
and a value of some integral type, bit positionpos
corresponds to the bit value1<<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
a
val
with binary representation11
leads to abitset<N> b
withb[0] = 1
,b[1] = 1
and remaining bits set to0
.这篇关于为什么的std :: bitset的Little Endian的方式暴露位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!