【问题标题】:Extracting bits from std::stringstream to std::bitset从 std::stringstream 中提取位到 std::bitset
【发布时间】:2013-11-29 01:24:59
【问题描述】:

根据我为std::bitset找到的一些文档:

它们也可以直接从二进制格式的流中插入和提取(参见适用的运算符)。

适用的运算符:

是,操作系统 basic_istream 或 basic_ostream 对象,分别从中提取或插入位集对象。插入/提取位集的格式是(适当加宽的)​​“0”和“1”字符序列。

template<class charT, class traits, size_t N>
   basic_istream<charT, traits>&
     operator>> (basic_istream<charT,traits>& is, bitset<N>& rhs);
 template<class charT, class traits, size_t N>
   basic_ostream<charT, traits>&
     operator<< (basic_ostream<charT,traits>& os, const bitset<N>& rhs);

这实质上意味着我们可以做类似的事情:

std::stringstream _stream(std::ios::binary);
{...}
std::bitset<16> a1;
std::bitset<8> a2;
_stream >> std::bin >> a1;
_stream >> std::bin >> a2;

在我看来,我只是在标准库中没有std::bin,其他一切都应该没问题。

我想知道有没有办法实现这个修饰符?

【问题讨论】:

  • 什么是std::bin?我从来没有听说过。
  • 您的流中有哪些数据?如果它是10 的字符串,这已经可以了。
  • 你引用的文档的意思是你可以做_stream &gt;&gt; a1; 没有任何特殊的IO操纵器,如std::bin(不存在)。但是,位集将由 0 和 1 表示,作为字符存储在流中。我认为没有任何标准方法可以将它们存储为实际位。
  • 简单看看here怎么用。是的,WTH 是std::bin??
  • 抱歉让你们(@remyabel、@Retired Ninja、@g-makulik)感到困惑,但我已经提到我们没有std::bin stl让梦想成真。 @jogojapan 我的流中有一些面向二进制的数据(假设有一个二进制文件),但没有预先安排的零和一。

标签: c++ stl std


【解决方案1】:

没有像 std::bin 流操纵器这样的东西,但是如果您想按位编写 std::bitset 内容,您可以尝试以下操作:

template<std::size_t num_bits>
void writeBits(ostream& os, const std::bitset<num_bits>& thebits)
{
    for(std::size_t bit_pos = 0; bit_pos < num_bits;)
    {
        unsigned char currentByte = 0;
        for(int currentBit = 0; 
            currentBit < sizeof(unsigned char) && 
            bit_pos < num_bits; 
            ++currentBit, ++bit_pos)
        {
            currentByte |= thebits[bit_pos] ? (0x80 >> currentBit) : 0;
        }
        os << currentByte;
    }
}

ideone 上查看完整示例。

如果您事先知道要阅读的 std::bitset&lt;&gt; 部分的大小,则反之亦然:

template<std::size_t num_bits>
void readBits(istream& is, std::bitset<num_bits>& thebits)
{
    thebits.reset();
    std::size_t total_bytes = num_bits / sizeof(unsigned char) + 1;
    std::size_t bit_pos = 0;
    for(std::size_t i = 0; 
        is && 
        i < total_bytes && 
        bit_pos < num_bits;
        ++i)
    {
        unsigned char currentByte = 0;
        if(is >> currentByte)
        {
            for(int currentBit = 0; 
                currentBit < sizeof(unsigned char) &&
                bit_pos < num_bits;
                ++currentBit, ++bit_pos)
            {
                thebits[bit_pos] = (currentByte &  (0x80 >> currentBit)) > 0;
            }
        }
    }
}

ideone 上查看完整示例。

【讨论】:

    猜你喜欢
    • 2011-01-19
    • 2017-03-04
    • 2019-10-24
    • 2018-12-03
    • 2016-09-10
    • 2014-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多