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

前端 未结 13 1841
情深已故
情深已故 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:00

    This should work:

    int original = ...;
    byte[] bytes = BitConverter.GetBytes(original);
    short firstHalf = BitConverter.ToInt16(bytes, 0);
    short secondHalf = BitConverter.ToInt16(bytes, 2);
    

    EDIT:

    tested with 0x7FFFFFFF, it works

    byte[] recbytes = new byte[4];
    recbytes[0] = BitConverter.GetBytes(firstHalf)[0];
    recbytes[1] = BitConverter.GetBytes(firstHalf)[1];
    recbytes[2] = BitConverter.GetBytes(secondHalf)[0];
    recbytes[3] = BitConverter.GetBytes(secondHalf)[1];
    int reconstituted = BitConverter.ToInt32(recbytes, 0);
    

提交回复
热议问题