我想将 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/