0

I need to fit the following structure into int64.

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

timrau
  • 22,578
  • 4
  • 51
  • 64
Stefan Steiger
  • 78,642
  • 66
  • 377
  • 442
  • Have you done the math for this option? Your hostname part will have a 50% chance of collision once 64 hosts are in the network, unless you're assigning them by hand. The random part has a 50% chance of collision when 512 ids are generated in the same "second" - which, due to clock drifts and corrections, may be longer than an actual *second*. – Stephen Cleary Aug 15 '10 at 13:42
  • it's actually 0.19 percent when 512 ids are generated. The hostname is assigned by hash, so it isn't random, so it's gonnna be lower than with pure randomness, assuming all different hostnames. But as I said in the other post, I'm probably going to increase the random number on the cost of the hostname. – Stefan Steiger Aug 16 '10 at 11:35

3 Answers3

7

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); }
    }
}
Anon.
  • 58,739
  • 8
  • 81
  • 86
7

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.
developmentalinsanity
  • 6,109
  • 2
  • 22
  • 18
4

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.

H H
  • 263,252
  • 30
  • 330
  • 514