惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
U
Unit 42
IT之家
IT之家
Y
Y Combinator Blog
T
Tailwind CSS Blog
B
Blog
大猫的无限游戏
大猫的无限游戏
博客园 - 叶小钗
Jina AI
Jina AI
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
I
InfoQ
J
Java Code Geeks
F
Fortinet All Blogs
T
The Blog of Author Tim Ferriss
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
H
Hackread – Cybersecurity News, Data Breaches, AI and More
人人都是产品经理
人人都是产品经理
腾讯CDC
Hugging Face - Blog
Hugging Face - Blog
GbyAI
GbyAI
博客园 - 司徒正美
The GitHub Blog
The GitHub Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
L
LangChain Blog

博客园 - zdleek

Vibe Coding(氛围编码/状态编程) 常用符号名称与读法 VSCode的【Microsoft C/C++ 扩展 】的使用简介[由DS给出] 小记VS code调用VC++编译器的环境配置 小记:DS给的一个lamda表达式例子 GPG4win 加解密使用笔记 Windows 11 Version 22H2 (Build 22621) 开发者资源下载 U盘启动多系统工具Ventoy 15种经典机器学习算法[转] 微软原版WIN10PE制作流程 [转]如何彻底关闭win10自动更新 C++模板的哲学 正则表达式简介 C++ 正则表达式使用例子 Lambda 表达式简介 在VC++中的使用gRPC编程 Win10下编译gRPC主要步骤 在VC++中使用ProtoBuf进行数据序列化的编程 Win10下编译ProtoBuf主要步骤
一段bitset的简单例子
zdleek · 2022-08-01 · via 博客园 - zdleek

C++ std::bitset的一段简单例子,例子代码输出结果如下:

Program returned: 0

b1:0000; b2:1010; b3:0011; b4:00000110

b1:0000; b2:1010; b3:1111; b4:00000110

b1:0000; b2:1010; b3:0100; b3.to_string():0100

#include <bitset>
#include <cstddef>
#include <cassert>
#include <iostream>
 
int main()
{
    typedef std::size_t length_t, position_t; // the hints
 
    // constructors:
    constexpr std::bitset<4> b1;
    constexpr std::bitset<4> b2{0xA}; // == 0B1010
    std::bitset<4> b3{"0011"}; // can't be constexpr yet
    std::bitset<8> b4{"ABBA", length_t(4), /*0:*/'A', /*1:*/'B'}; // == 0B0000'0110
 
    // bitsets can be printed out to a stream:
    std::cout << "b1:" << b1 << "; b2:" << b2 << "; b3:" << b3 << "; b4:" << b4 << '\n';
 
    // bitset supports bitwise operations:
    b3 |= 0b0100; assert(b3 == 0b0111);
    b3 &= 0b0011; assert(b3 == 0b0011);
    b3 ^= std::bitset<4>{0b1100}; assert(b3 == 0b1111);
 
     std::cout << "b1:" << b1 << "; b2:" << b2 << "; b3:" << b3 << "; b4:" << b4 << '\n';

    // operations on the whole set:
    b3.reset(); assert(b3 == 0);
    b3.set(); assert(b3 == 0b1111);
    assert(b3.all() && b3.any() && !b3.none());
    b3.flip(); assert(b3 == 0);
 
    // operations on individual bits:
    b3.set(position_t(1), true); assert(b3 == 0b0010);
    b3.set(position_t(1), false); assert(b3 == 0);
    b3.flip(position_t(2)); assert(b3 == 0b0100);
    b3.reset(position_t(2)); assert(b3 == 0);
 
    // subscript operator[] is supported:
    b3[2] = true; assert(true == b3[2]);
 
    // other operations:
    assert(b3.count() == 1);
    assert(b3.size() == 4);
    assert(b3.to_ullong() == 0b0100ULL);
    assert(b3.to_string() == "0100");

    std::cout << "b1:" << b1 << "; b2:" << b2 << "; b3:" << b3 << "; b3.to_string():" << b3.to_string() << '\n';
}