我必须在VB.net中将16位Int打包并解压缩到Ushort
这就是我认为我能做到的事情(不起作用,给我溢出异常)
'Pack Int16 into ushort '
Dim usPacked = CType(Data, UShort)
'unpack Int16 from ushort '
Dim unpacked = CType(data,Int16)
谢谢!
答案 0 :(得分:1)
您可以使用旧的Union解决方案
<StructLayout(Runtime.InteropServices.LayoutKind.Explicit)> _
Structure s1
<FieldOffset(0)> Public AsShort As Short
<FieldOffset(0)> Public AsUShort As UShort
End Structure
Dim v1 = GetTheShortValue()
Dim v2 = new s1
v2.AsShort = v1
Dim v3 As UShort = v2.AsUShort
答案 1 :(得分:0)
编辑:Jared's answer比我的这个更好:(
当您尝试将负数放入UShort时,或者当您尝试将数字超过32,767放入Short时,您将获得overflow。一种解决方案是使用Long作为中介。
'Pack Int16 into ushort '
Dim usPacked = CType(CLng(nData) + 32768, UShort)
'unpack Int16 from ushort '
Dim unpacked = CType(CLng(usPacked) - 32768, Int16)