And that essentially 'halves' the maximum value you can have in that variable. Remember a signed value always sacrifices one bit to store the negative state of the number. There can only be 1 negative output out of two. => ((ushort)(value / 0x10000), (ushort)(value % 0x10000)) Īs for signs, you have to decide how you want to split the data. Or an expression body version of it: public (ushort, ushort) SplitToUShorts(uint value) I did not use bitwise operators but for unsigned values, this may work: public (ushort, ushort) SplitToUnsignedShorts(uint value) 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 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.įrom 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. The first field (DWord.Value) would be the 32bit integer, with an offset of 0 (zero). With these two attributes in use you can create overlapping fields, aka unions. Using the StructLayout as explicit onto a structure requires you to provide the positioning of each field (by byte offset) with the FieldOffset attribute 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. Public Sub New(ByVal high as Int16, ByVal low as Int16) Signed would be the same just using those types instead _ Public Sub New(ByVal high as UInt16, ByVal low as UInt16) However, it uses unsafe code.Ĭorrection: word is 16bit, dword is 32bit _
GSPLIT SHORTS CODE
I also created another answer, based on code of BitConverter class, optimized for this particular task. Personally I like Agg's answer, because my code is more complicated, and Jon's would cause an overflow exception in checked environment. It is because by default C# compiler uses unchecked operations and VB.NET checked. NET CType(&Hffff, Int16) causes overflow, and (short)0xffff gives -1 (without overflow). Jon's answer, translated into Visual Basic, and without overflow: Module Module1įunction MakeSigned(ByVal x As UInt16) As Int16ĭim juniorBits As Int16 = CType(x And &H7FFF, Int16)ĭim firstHalfUnsigned As UInt16 = CType(original > 16, UInt16)ĭim secondHalfUnsigned As UInt16 = CType(original And &HFFFF, UInt16)ĭim firstHalfSigned As Int16 = MakeSigned(firstHalfUnsigned)ĭim secondHalfSigned As Int16 = MakeSigned(secondHalfUnsigned)