为什么我的短文在VB.net中包含4字节

时间:2021-12-08 13:58:47

According to MSDN a Short datatype consists of two bytes: https://msdn.microsoft.com/en-us/library/47zceaw7.aspx

根据MSDN,一个短数据类型由两个字节组成:https://msdn.microsoft.com/en-us/library/47zceaw7.aspx

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

但是如果我定义一个短变量,内容总是4个字节:&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

1 个解决方案

#1


5  

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

因为短符号是有符号的,所以最重要的位是为符号预留的。因此,在带符号的短代码中可以存储的最高值是&H7FFF或Int16.MaxValue

If you want to utilise all 16 bits then you need to use an Unsigned Short (UInt16)

如果您想使用所有16位,那么您需要使用未签名的短(UInt16)

So this Fails:

所以这个操作失败:

Dim crc As Short = CShort(&HFFFF) 

But this Works:

但是这个工作原理:

Dim crc As UShort = CUShort(&HFFFF) 

#1


5  

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

因为短符号是有符号的,所以最重要的位是为符号预留的。因此,在带符号的短代码中可以存储的最高值是&H7FFF或Int16.MaxValue

If you want to utilise all 16 bits then you need to use an Unsigned Short (UInt16)

如果您想使用所有16位,那么您需要使用未签名的短(UInt16)

So this Fails:

所以这个操作失败:

Dim crc As Short = CShort(&HFFFF) 

But this Works:

但是这个工作原理:

Dim crc As UShort = CUShort(&HFFFF)