C++ 位操作。 6 个整数合为一个 unsigned long long

标签 c++ bit-manipulation bit

我想将 6 个整数放入一个 unsigned long long 变量中。然后,我想从 long long 变量位范围中读取这些整数。我写了这样的东西,但它返回负输出

unsigned long long encode(int caller, int caller_zone,
int callee, int callee_zone,
int duration, int tariff) {

struct CallInfo
{
 int caller : 17;
 int caller_zone : 7;
 int callee : 17;
 int callee_zone : 7;
 int duration : 13;
 int tariff : 3;
};

CallInfo info = { caller, caller_zone, callee, callee_zone, duration, tariff};

cout << info.caller << endl;
cout << info.caller_zone << endl;   
}

最佳答案

为此使用位字段要容易得多,例如

struct CallInfo
{
    unsigned int caller : 17;
    unsigned int caller_zone : 7;
    unsigned int callee : 17;
    unsigned int callee_zone : 7;
    unsigned int duration : 13;
    unsigned int tariff : 3;
};

你真的不需要编码函数,因为你可以写,例如

CallInfo info = { /* ... initialise fields here ... */ };

然后以正常方式访问字段:

info.caller = 0;
info.caller_zone = info.callee_zone;
// ...

关于C++ 位操作。 6 个整数合为一个 unsigned long long,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23472633/

相关文章:

c++ - 如何选择图像旋转轴,Magick++?

c++ - Windows:检查命名管道是否存在

c++ - 程序接收信号 SIGILL,非法指令

c - 应该使用类型转换来设置位域吗?

c++ - 我不明白为什么我在按位或短字符和字符时得到这个结果

java - 如何向文件中写入不是 8 倍数的位数

java - 字符串中的空终止

JavaScript trunc() 函数

javascript - 给定低位和高位,如何生成 64 位二进制补码整数?

c++ - 从 char 数组转换/提取整数