According to MSDN a Short
datatype consists of two bytes: https://msdn.microsoft.com/en-us/library/47zceaw7.aspx
But if I define a 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's the deal with this? Why does my Short
doesn't take two bytes?
MWE added:
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
It is because a Short
is signed, so the most significant bit is reserved for the sign. Therefore the highest value you can store in a signed short is &H7FFF
or Int16.MaxValue
If you want to utilise all 16 bits then you need to use an Unsigned Short (UInt16
)
So this Fails:
Dim crc As Short = CShort(&HFFFF)
But this Works:
Dim crc As UShort = CUShort(&HFFFF)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With