C ++位操作。 6个整数成一个无符号长的长整数

时间:2014-05-05 12:36:32

标签: c++ bit-manipulation bit

我想将6个整数放入一个无符号长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;   
}

1 个答案:

答案 0 :(得分:2)

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

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;
// ...