位域与位集 [英] Bit field vs Bitset

查看:80
本文介绍了位域与位集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将位存储在数组(如结构)中.因此,我可以采用以下两种方法之一

I want to store bits in an array (like structure). So I can follow either of the following two approaches

方法1(AN 1)

struct BIT
{
   int data : 1
};

int main()
{
   BIT a[100];
   return 0;
}

方法2(AN 2)

int main()
{
    std::bitset<100> BITS;
    return 0;
}

为什么有人会比AN 1更喜欢AN 2?

Why would someone prefer AN 2 over AN 1?

推荐答案

因为方法nr.2实际上使用100位存储,外加一些非常小的(恒定)开销,而nr.1通常每个 Bit 结构使用四个字节的存储空间.通常,按照C ++标准, struct 至少大一个字节.

Because approach nr. 2 actually uses 100 bits of storage, plus some very minor (constant) overhead, while nr. 1 typically uses four bytes of storage per Bit structure. In general, a struct is at least one byte large per the C++ standard.

#include <bitset>
#include <iostream>

struct Bit { int data : 1; };

int main()
{
    Bit a[100];
    std::bitset<100> b;
    std::cout << sizeof(a) << "\n";
    std::cout << sizeof(b) << "\n";
}

打印

400
16

除此之外, bitset 将您的位数组包装成一个漂亮的具有许多有用操作的对象表示.

Apart from this, bitset wraps your bit array in a nice object representation with many useful operations.

这篇关于位域与位集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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