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

前端 未结 13 1818
情深已故
情深已故 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 11:59

    You can use StructLayout in VB.NET:

    correction: word is 16bit, dword is 32bit

     _
       Public Structure UDWord
           Public Value As UInt32
           Public High As UInt16
           Public Low As UInt16
    
          Public Sub New(ByVal value As UInt32)
             Me.Value = value
          End Sub
    
          Public Sub New(ByVal high as UInt16, ByVal low as UInt16)
             Me.High = high
             Me.Low = low
          End Sub
       End Structure
    

    Signed would be the same just using those types instead

     _
       Public Structure DWord
           Public Value As Int32
           Public High As Int16
           Public Low As Int16
    
          Public Sub New(ByVal value As Int32)
             Me.Value = value
          End Sub
    
          Public Sub New(ByVal high as Int16, ByVal low as Int16)
             Me.High = high
             Me.Low = low
          End Sub
       End Structure
    

    EDIT:

    I've kind of rushed the few times I've posted/edited my anwser, and yet to explain this solution, so I feel I have not completed my answer. So I'm going to do so now:

    Using the StructLayout as explicit onto a structure requires you to provide the positioning of each field (by byte offset) [StructLayoutAttribute] with the FieldOffset attribute [FieldOffsetAttribute]

    With these two attributes in use you can create overlapping fields, aka unions.

    The first field (DWord.Value) would be the 32bit integer, with an offset of 0 (zero). To split this 32bit integer you would have two additional fields starting again at the offset of 0 (zero) then the second field 2 more bytes off, because a 16bit (short) integer is 2 bytes a-peice.

    From what I recall, usually when you split an integer they normally call the first half "high" then the second half "low"; thus naming my two other fields.

    With using a structure like this, you could then create overloads for operators and type widing/narrowing, to easily exchange from say an Int32 type to this DWord structure, aswell as comparasions Operator Overloading in VB.NET

提交回复
热议问题