Is there a nice way to split an int into two shorts (.NET)?

前端 未结 13 1816
情深已故
情深已故 2021-01-01 11:25

I think that this is not possible because Int32 has 1 bit sign and have 31 bit of numeric information and Int16 has 1 bit sign and 15 bit of numeric information

13条回答
  •  渐次进展
    2021-01-01 12:16

    You can use StructLayout to do this:

    [StructLayout(LayoutKind.Explicit)]
            struct Helper
            {
                [FieldOffset(0)]
                public int Value;
                [FieldOffset(0)]
                public short Low;
                [FieldOffset(2)]
                public short High;
            }
    

    Using this, you can get the full Value as int , and low part, hight part as short.

    something like:

    var helper = new Helper {value = 12345};
    

提交回复
热议问题