位域
今天遇到一个题要求用一个字节存储两个变量信息并进行相应的计算,发现了一种专业课学过却很少使用的一种结构声明方式,称为位域。示例如下:
struct {
unsigned char a : 4;
unsigned char b : 4;
}i;
这种声明方式得到的变量是指定位数的,可以比较方便地处理一些问题。
下面说下这种结构体的性质:
cout << sizeof(i);//输出1
i.a = 2;
i.b = 1;
cout << *((unsigned int*)&i);//输出18
也就是说,示例中的结构体,相当于一个unsigned char变量,并且a、b分别表示unsigned char变量的低4位、高4位。
另外,位域结构体还有多种类型变量的声明、指定对齐方式等多种用法,可搜索位域了解更多,这里不再展开。
bitset类
C++标准库中提供了bitset类,在需要使用位变量时推荐使用bitset类而不是位域,毕竟模板类有更多玩法且使用方便。
具体用法可点相应链接查看示例代码。
std::bitset
Defined in header <bitset>
The class template bitset represents a fixed-size sequence of N bits. Bitsets can be manipulated by standard logic operators and converted to and from strings and integers.
Element access | |
---|---|
[ ] | 访问指定位 |
test | 同[ ],但会进行越界检测 |
all any none | all全部位为true则返回true,否则返回false;其余类似 |
count | 返回位为true的个数 |
Capacity | |
size | |
Modifiers | |
& | ^ ~ | 与 或 异或 |
<<= >>= << >> | 移位操作符 |
set | 设某位为true |
reset | 设某位为false |
flip | 翻转变量或某位 |
Conversions | |
to_string | 转换为string返回,可指定位表示符 |
to_ulong | |
to_ullong |
网友评论