命名空间
变体
操作

operator<<,>>(std::bitset)

来自 cppreference.cn
< cpp‎ | 工具库‎ | bitset
 
 
 
 
定义于头文件 <bitset>
template< class CharT, class Traits, std::size_t N >

std::basic_ostream<CharT, Traits>&

    operator<<( std::basic_ostream<CharT, Traits>& os, const std::bitset<N>& x );
(1)
template< class CharT, class Traits, std::size_t N >

std::basic_istream<CharT, Traits>&

    operator>>( std::basic_istream<CharT, Traits>& is, std::bitset<N>& x );
(2)

将 bitset 插入或提取到字符流中。

1) 将 bitset x 写入字符流 os,如同先将其转换为 std::basic_string<CharT, Traits>(使用 to_string()),然后使用 operator<<(它是字符串的 FormattedOutputFunction)将其写入 os
用于表示一和零的字符通过调用 std::use_facet<std::ctype<CharT>>(os.getloc()).widen() 并以 '1''0' 作为参数,从当前所浸润的区域设置中获取。
2) 表现为 FormattedInputFunction。在构造并检查哨兵对象(可能跳过前导空白)后,从 is 中提取最多 N 个字符,并将这些字符存储在 bitset x 中。
提取字符直到满足以下任一条件:
  • 已读取 N 个字符,
  • is 中发生文件结束,或
  • 下一个字符既不是 is.widen('0') 也不是 is.widen('1')
如果 N > 0 且未提取任何字符,则调用 is.setstate(ios_base::failbit)

目录

[编辑] 参数

os - 要写入的字符流
is - 要读取的字符流
x - 要读取或写入的 bitset

[编辑] 返回值

1) os
2) is

[编辑] 示例

#include <bitset>
#include <iostream>
#include <sstream>
 
int main()
{
    std::string bit_string = "001101";
    std::istringstream bit_stream(bit_string);
 
    std::bitset<3> b1;
    bit_stream >> b1; // reads "001", stream still holds "101"
    std::cout << b1 << '\n';
 
    std::bitset<8> b2;
    bit_stream >> b2; // reads "101", populates the 8-bit set as "00000101"
    std::cout << b2 << '\n';
}

输出

001
00000101

[编辑] 缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

缺陷报告 应用于 发布时的行为 正确的行为
LWG 303 C++98 is 提取单字节字符,但 CharT 可以有多个字节
is 提取单字节字符,但 CharT 可以有多个字节
提取 CharT 并将其与加宽的 '0''1' 进行比较
提取 CharT 并将其与加宽的 '0''1' 进行比较
LWG 396 C++98 operator<< 写入的内容与区域设置无关 写入加宽的 '0''1'
LWG 3199 C++98 提取 std::bitset<0> 总是设置 failbit 此类提取从不设置 failbit

[编辑] 参阅

执行二进制左移和右移
(公共成员函数) [编辑]