开发者

How to fit a structure in an int64?

I need to fit the following structure into int64.开发者_StackOverflow

day  9 bit (0 to 372)
year 8 bit (2266-2010 = 256 y)
seconds  17 bit (24*60*60=86400 s)
hostname 12 bit (2^12=4096)
random 18 bit (2^18=262144)

How do I make such a structure fit in an int64? All items are numberic, and of the specified bit size


Just bitwise-or the components together with appropriate shifts.

int64 combined = random | (hostname << 18) | (seconds << (18+12)) ... etc.

Get things out by shifting and and-ing them.

random = combined & 0x3FFFF
hostname = (combined >> 18) & 0xFFF;
etc.


Typically you'd declare a structure with one int64 field, and multiple properties which access just the relevant bits of that field.

So like:

struct MyStruct
{
    int64 _data

    public short Day
    {
        get { return (short)(_data >> 57); }
    }
}


You tagged this C++ and C#, very different options for those two.

In C++ you can use bit-fields:

// from MSDN
struct Date 
{
   unsigned nWeekDay  : 3;    // 0..7   (3 bits)
   unsigned nMonthDay : 6;    // 0..31  (6 bits)
   unsigned nMonth    : 5;    // 0..12  (5 bits)
   unsigned nYear     : 8;    // 0..100 (8 bits)
};

In C# you will have to bit-shift yourself, as in the other answers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜