Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my Short containing 4 bytes in VB.net

Tags:

.net

vb.net

short

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
like image 509
bitlischieber Avatar asked Mar 24 '16 10:03

bitlischieber


1 Answers

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) 
like image 173
Matt Wilko Avatar answered Nov 15 '22 08:11

Matt Wilko