[英]how to create an array of elements with 1 bit in size in c++
In c / c++, we can define a variable with 1 bit in memory: like unsigned char value : 1
; 在c / c ++中,我们可以在内存中定义一个1位的变量:就像unsigned
char value : 1
;
Is there a way to declare an array of 1 bit elements? 有没有办法声明一个1位元素的数组? like in sudo code below:
像下面的sudo代码一样:
unsigned char : 1 data[10];
The problem is that in most implementations, the 1 bit variable will still occupy 1 byte of memory because that's the way the memory is addressed. 问题在于,在大多数实现中,1位变量仍将占用1字节的内存,因为这是解决内存的方式。 If you have a big array of such values, however, then you can work around that.
但是,如果您有大量此类值,则可以解决此问题。 One such solution is
std::bitset
. 一种这样的解决方案是
std::bitset
。 You can make one like this: 您可以像这样制作一个:
#include <bitset>
std::bitset<64> data;
You can manipulate bits using the set
, reset
and flip
operations (setting it to 1, 0 or toggling it). 您可以使用
set
, reset
和flip
操作(将其设置为1、0或切换)来操纵位。 You can access a bit using []
, for instance 例如,您可以使用
[]
进行访问
if (data[5]) { ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.