Sign extend 16-bit value to Integer

  • Thread starter Thread starter Jack Jackson
  • Start date Start date
J

Jack Jackson

What is the best way to sign extend a 16-bit value (such as half of
the lparam value in WM_NCxxx messages) into an Integer?

Currently I test for the 8000 bit and if set OR in FFFF0000, but it
seems like there should be some built-in way to do this.
 
Yes, but how do I get the original 16-bit value into a Short?

The value I am starting with is 16-bits of an IntPtr. I can convert
the IntPtr to Integer, but can't find any way to initialize a Short
with 16-bits from the Integer when the high order bit of the 16-bits
is set.

My code is something like this:

Protected Overrides Sub WndProc(ByRef m As
System.Windows.Forms.Message)

Select Case m.Msg
Case &H201
' I can convert the IntPtr to Integer
Dim lp As Integer = Convert.ToInt32(m.LParam)

' But if I try to convert 16 bits of that to a Short,
' I get an exception if the high order bit of the 16-bit
' value is set (value is negative).
Dim x As Short = Convert.ToShort(lp And &HFFFF)
 
Try the following example for BitConverter to see if this works for you.

Sub Main()
Dim x32 As Int32 = &H432312AF
Dim a16, b16 As Int16 ' if you want 2 byte ints
Dim a32, b32 As Int32 ' if you want 4 byte ints
Dim ba As Byte() = BitConverter.GetBytes(x32)

a16 = BitConverter.ToInt16(ba, 0)
b16 = BitConverter.ToInt16(ba, 2)

a32 = a16 : b32 = b16

Console.Out.WriteLine(String.Format("{0:x} {1:x} {2:x}", x32, a32, b32))
Console.In.ReadLine()

End Sub
 
Thanks, that works fine.

Try the following example for BitConverter to see if this works for you.

Sub Main()
Dim x32 As Int32 = &H432312AF
Dim a16, b16 As Int16 ' if you want 2 byte ints
Dim a32, b32 As Int32 ' if you want 4 byte ints
Dim ba As Byte() = BitConverter.GetBytes(x32)

a16 = BitConverter.ToInt16(ba, 0)
b16 = BitConverter.ToInt16(ba, 2)

a32 = a16 : b32 = b16

Console.Out.WriteLine(String.Format("{0:x} {1:x} {2:x}", x32, a32, b32))
Console.In.ReadLine()

End Sub
 
Jack,

Copied from a message in this newsgroup from Tom Spink

\\\
Dim strText = "The String Being Measured"
Dim g As Graphics = Me.CreateGraphics
Dim sfSize As SizeF = g.MeasureString(strText, Me.Font)

MsgBox("Width: " & sfSize.Width & vbCrLf & "Height: " & sfSize.Height)
///

Cor
 
Back
Top