简体   繁体   English

如何使用6位存储值?

[英]How can i use 6 bits to store value?

My data unit (a network packet header) i am currently working on has 2 flags in its definition, stored in a byte field and accessed via bitwise operators. 我当前正在使用的数据单元(网络数据包头)的定义中有2个标志,存储在字节字段中,并通过按位运算符进行访问。 Unfortunately, i need only 2 bits and thinking what i can do with other 6 bits? 不幸的是,我只需要2位,然后思考我可以用其他6位做什么? Can i use them to store number? 我可以用它们存储号码吗?

Can i use them to store some internal state code (value range smaller than char ?) and do not just waste them. 我可以使用它们存储一些内部状态代码 (值范围小于char吗?),而不仅仅是浪费它们。

Is there any data types smaller than byte and how can i use them in C++? 是否有小于字节的数据类型,我该如何在C ++中使用它们? If no, should i waste those bits and left them without meaning? 如果否,我是否应该浪费这些位,并让它们毫无意义?

You could use a bit field, as described here . 你可以使用一些领域,如所描述这里

Adapted from that page: 从该页面改编而成:

#include <iostream>
struct S {
 // 6-bit unsigned field,
 // allowed values are 0...63
 unsigned int b : 6;
};
int main()
{
    S s = {7};
    ++s.b;
    std::cout << s.b << '\n'; // output: 8
}

In C++, there is no datatype smaller than a char , which is - by definition - one byte. 在C ++中,没有任何数据类型小于char (根据定义为1个字节)。 However, you do not need a dedicated datatype to access the bits of a value. 但是,您不需要专用的数据类型来访问值的位。 Bitwise logic and Bitwise Shift operators are sufficient. 按位逻辑和按位移位运算符就足够了。

If you cannot live with sacrificing 6 bits (this is assuming 8-bit bytes) you might want to consider the std::vector<bool> specialization. 如果不能忍受牺牲6位(假设8位字节),则可能需要考虑std :: vector <bool>特化 Note, though, that there are a number of restrictions and differences to a regular std::vector . 但是请注意,常规std :: vector有很多限制和差异。

Another option to make individual (consecutive) bits of a datatype accessible by name is to use bit fields : 使名称可以访问数据类型的各个(连续)位的另一种选择是使用位字段

struct S {
    unsigned int flags : 2;
    unsigned int state : 6;
};
static_assert( sizeof( S ) == 1, "Packing is implementation-defined." );

This declares a structure that can hold two pieces of information: flags and state , which occupy 2 and 6 bits, respectively. 这声明了一个结构,该结构可以容纳两条信息: flagsstate ,分别占据2位和6位。 Adjacent bit fields are usually packed together (although this behavior is implementation-defined). 通常将相邻的位字段打包在一起(尽管此行为是实现定义的)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM