为什么 std::bitset 以小端方式公开位?

Why does std::bitset expose bits in little-endian fashion?(为什么 std::bitset 以小端方式公开位?)

本文介绍了为什么 std::bitset 以小端方式公开位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用 std::bitset<N>::bitset( unsigned long long ) 时,它会构造一个位集,当我通过 operator[] 访问它时,这些位似乎以小端方式排序.示例:

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. Example:

std::bitset<4> b(3ULL);
std::cout << b[0] << b[1] << b[2] << b[3];

打印 1100 而不是 0011 即结束(或 LSB)位于小(低)地址,索引 0.

prints 1100 instead of 0011 i.e. the ending (or LSB) is at the little (lower) address, index 0.

查看标准,它说

将前M位位置初始化为val

程序员自然会想到从 LSB 到 MSB(从右到左)的二进制数字.所以前 M 位位置可以理解为 LSB → MSB,所以位 0 将位于 b[0].

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

E1的值<<<E2E1 左移 E2 位位置;空出的位用零填充.

The value of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are zero-filled.

这里必须将 E1 中的位解释为从 MSB → LSB 然后左移 E2 次.如果它是从 LSB → MSB 写的,那么只有右移 E2 次会得到相同的结果.

Here one has to interpret the bits in E1 as going from MSB → LSB and then left-shift E2 times. Had it been written from LSB → MSB, then only right-shifting E2 times would give the same result.

令我惊讶的是,在 C++ 的其他任何地方,该语言似乎都投射出自然(英语;从左到右)的书写顺序(在进行移位等按位运算时).为什么这里不一样?

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?

推荐答案

就标准而言,没有字节序的概念.说到std::bitset[template.bitset]/3定义了bit position:

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:

bitset 类的对象和值之间进行转换时一些整数类型,位位置 pos对应位值1<.两位或多位对应的整数值为和它们的位值.

When converting between an object of class bitset<N> and a value of some integral type, bit position pos corresponds to the bit value 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

将第一个M 位位置初始化为val

具有二进制表示的 val 11 导致 bitset;bb[0] = 1b[1] = 1 和其余位设置为 0.

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.

这篇关于为什么 std::bitset 以小端方式公开位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:为什么 std::bitset 以小端方式公开位?

基础教程推荐