user3003914
user3003914

Reputation: 1

C++ bits operation. 6 integers into one unsigned long long

I would like to put 6 ints into one unsigned long long variable. Then, I would like to read these integers from long long variable bits range. I wrote something like this but it returns negative output

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;   
}

Upvotes: 0

Views: 189

Answers (1)

Paul R
Paul R

Reputation: 213190

It's much easier to use bit fields for this, e.g.

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;
};

You would not really need an encode function, as you could just write, e.g.

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

and then access fields in the normal way:

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

Upvotes: 2

Related Questions