为什么的std :: bitset的Little Endian的方式暴露位? [英] Why does std::bitset expose bits in little-endian fashion?

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

问题描述

当我使用和std :: bitset< N> ::位集(无符号很长很长)此构造一个bitset,当我通过运算符[] 中,位似在小端的方式进行订购。例如:

 和std :: bitset 4;> B(3ULL);
性病::法院LT&;< B [0]&下;&下; B〔1];&下; B〔2〕&下;&下; B〔3〕;

打印 1100 而不是 0011 即结束(或LSB)是小(低)地址,指数0。

仰望的标准,它说:


  

在初始化 VAL

的前M位的位置到相应的位值

程序员自然会想到从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 二进制重新presentation 11 导致位集&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 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];

prints 1100 instead of 0011 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 is E1 left-shifted E2 bit positions; 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. Had it been written from LSB → MSB, then only right-shifting E2 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 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

initializing the first M bit positions to the corresponding bit values in 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.

这篇关于为什么的std :: bitset的Little Endian的方式暴露位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆