Why is my Short contains 4 bytes in VB.net

According to MSDN, the Short data type consists of two bytes: https://msdn.microsoft.com/en-us/library/47zceaw7.aspx

But if I define the Short variable, the content is always 4 bytes: & HFFFFFFFF

 Dim crc As Short = CShort(&HFFFFS) ' crc = &HFFFFFFFF Dim crc As Short = &HFFFFS ' crc = &HFFFFFFFF 

And this statement even gives me an error:

 Dim crc As Short = CShort(&HFFFF) ' Error: Constant expression not representable in type 'Short' 

What is the reason for this? Why is my Short not accepting two bytes?

Added by MWE:

 Public Function CRC16(ByVal dataFrame As Byte(), ByVal dataLength As Int16) As Int16 Dim index As Int16 Dim crc As Short = &HFFFFS For iCount As Int16 = 0 To CShort(dataLength - 1) index = (crc >> 8) Xor dataFrame(iCount) crc = CShort(&HFFFF And ((crc << 8) Xor CRC_Table(index))) Next Return crc End Function 
+5
source share
1 answer

This is because Short signed , so the most significant bit is reserved for the character. Therefore, the highest value that you can save in a signed short text is &H7FFF or Int16.MaxValue

If you want to use all 16 bits, you need to use Unsigned Short ( UInt16 )

So this does not work:

 Dim crc As Short = CShort(&HFFFF) 

But it works:

 Dim crc As UShort = CUShort(&HFFFF) 
+5
source

Source: https://habr.com/ru/post/1245691/


All Articles