views:

221

answers:

2

I have to pack and unpack a 16bit Int from/into a Ushort in VB.net

This is how I thought I could do it (doesn't work, gives me overflow exception)

'Pack Int16 into ushort '
Dim usPacked = CType(Data, UShort)

'unpack Int16 from ushort '
Dim unpacked = CType(data,Int16)

Thanks!

A: 

EDIT: Jared's answer is better than this one of mine :(

  • UShort can store integers from 0 through 65,535.
  • Short can store integers from -32,768 through 32,767.
  • Long can store integers from about -2 billion to +2 billion.

You'll get an overflow when you try to put negative numbers into a UShort, or when you try to put numbers over 32,767 into a Short. One solution is to use a Long as an intermediary.

  'Pack Int16 into ushort '  
  Dim usPacked = CType(CLng(nData) + 32768, UShort)    
  'unpack Int16 from ushort '  
  Dim unpacked = CType(CLng(usPacked) - 32768, Int16)
MarkJ
+1  A: 

You can use the old Union solution

<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
JaredPar