代码之家  ›  专栏  ›  技术社区  ›  Stefan Steiger Marco van de Voort

如何使结构适合int64?

  •  0
  • Stefan Steiger Marco van de Voort  · 技术社区  · 15 年前

    我需要在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)
    

    所有项目都是数字的,并且具有指定的位大小

    3 回复  |  直到 13 年前
        1
  •  7
  •   developmentalinsanity    15 年前

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

    把东西移开,然后把它们放出来。

    random = combined & 0x3FFFF
    hostname = (combined >> 18) & 0xFFF;
    etc.
    
        2
  •  7
  •   Anon.    15 年前

    通常,您会声明一个结构,其中包含一个int64字段和多个属性,这些属性只访问该字段的相关位。

    struct MyStruct
    {
        int64 _data
    
        public short Day
        {
            get { return (short)(_data >> 57); }
        }
    }
    
        3
  •  4
  •   Henk Holterman    15 年前

    你标记了这个C++和C,这两个选项非常不同。

    在C++中你可以使用 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)
    };
    

    在C#你将不得不改变自己,在其他答案。

    推荐文章