为什么std :: bitset的位以相反的顺序? [英] Why are the bits of a std::bitset in reverse order?

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

问题描述

为什么bitset以相反的顺序存储位?多次绑定后,我终于写了这个binary_to_dec。可以简化吗?

  int binary_to_dec(std :: string bin)
{
std :: bitset< ; 8>位;

int c = bin.size();

for(size_t i = 0; i {
bit.set(c-1, i] - '0'?true:false));
}

return bit.to_ulong();
}


解决方案

您认为是反向顺序,因为即使字符串的字符以增加的索引顺序排列,我们仍以递减的顺序写入数字的数字。 / p>

如果我们以小端序顺序写入数字,那么你不会有这种混淆,因为字符串的索引0处的字符将表示bitset的位0。但是我们用大端顺序写我们的数字。恐怕我不知道导致这项公约的人类历史的细节。 (请注意,任何特定的CPU用来存储多字节数字的字节序是不相关的,我说的是我们在显示数字以供人阅读时使用的字节序)。



例如,如果我们用二进制数来写十进制数12,我们得到1100.最低有效位在右边。我们称之为位0。但是如果我们把它放在一个字符串中,1100,则该字符串的索引0处的字符表示位3,而不是位0。我们创建了一个bitset,位的顺序与字符相同, to_ulong 将返回3而不是12。



bitset类有一个接受 std :: string 的构造函数,但它期望字符的索引与该位的索引匹配,因此您需要反转串。试试这个:

  int binary_to_dec(std :: string const& bin)
{
std ::位组8。 bit(std :: string(bin.rbegin(),bin.rend()));
return bit.to_ulong();
}


Why does bitset store the bits in reverse order? After strugging many times I have finally written this binary_to_dec. Could it simplified?

int binary_to_dec(std::string bin)
{
    std::bitset<8> bit;

    int c = bin.size();

    for (size_t i = 0; i < bin.size(); i++,c--)
    {
        bit.set(c-1, (bin[i]-'0' ? true : false));
    }

    return bit.to_ulong();
}

解决方案

Bitset stores its numbers in what you consider to be "reverse" order because we write the digits of a number in decreasing order of significance even though the characters of a string are arranged in increasing index order.

If we wrote our numbers in little-endian order, then you wouldn't have this confusion because the character at index 0 of your string would represent bit 0 of the bitset. But we write our numbers in big-endian order. I'm afraid I don't know the details of human history that led to that convention. (And note that the endianness that any particular CPU uses to store multi-byte numbers is irrelevant. I'm talking about the endianness we use when displaying numbers for humans to read.)

For example, if we write the decimal number 12 in binary, we get 1100. The least significant bit is on the right. We call that "bit 0." But if we put that in a string, "1100", the character at index 0 of that string represents bit 3, not bit 0. If we created a bitset with the bits in the same order as the characters, to_ulong would return 3 instead of 12.

The bitset class has a constructor that accepts a std::string, but it expects the index of the character to match the index of the bit, so you need to reverse the string. Try this:

int binary_to_dec(std::string const& bin)
{
  std::bitset<8> bit(std::string(bin.rbegin(), bin.rend()));
  return bit.to_ulong();
}

这篇关于为什么std :: bitset的位以相反的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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