Skip to content

Instantly share code, notes, and snippets.

@wolf99
Last active April 20, 2017 12:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wolf99/8218e40d10d914238201fff353930080 to your computer and use it in GitHub Desktop.
Save wolf99/8218e40d10d914238201fff353930080 to your computer and use it in GitHub Desktop.
VB.NET extensions to allow conversion from an unsigned type to the equivalent signed type, and vice versa, while preserving the sign bit, by using a structure with explicit layout to simulate a union.
Option Strict On
Option Explicit On
Imports System.Runtime.InteropServices
Imports System.Runtime.CompilerServices
Module ConvertWithSign
' These extensions allow conversion from an unsigned type to the equivalent
' signed type, and vice versa, while preserving the sign bit.
'
' Usage:
' Dim x As UInt16 = 65535
' Console.WriteLine(x.ToSigned().ToString())
' 'Prints "-1"
<StructLayout(LayoutKind.Explicit)>
Private Structure NumberUnion
<FieldOffset(0)> Public Int8 As SByte
<FieldOffset(0)> Public UInt8 As Byte
<FieldOffset(0)> Public Int16 As Int16
<FieldOffset(0)> Public UInt16 As UInt16
<FieldOffset(0)> Public Int32 As Int32
<FieldOffset(0)> Public UInt32 As UInt32
<FieldOffset(0)> Public Int64 As Int64
<FieldOffset(0)> Public UInt64 As UInt64
End Structure
<Extension()> Public Function ToSigned(a As Byte) As SByte
Return New NumberUnion With {.UInt8 = a}.Int8
End Function
<Extension()> Public Function ToUnsgined(a As SByte) As Byte
Return New NumberUnion With {.Int8 = a}.UInt8
End Function
<Extension()> Public Function ToSigned(a As UInt16) As Int16
Return New NumberUnion With {.UInt16 = a}.Int16
End Function
<Extension()> Public Function ToUnsigned(a As Int16) As UInt16
Return New NumberUnion With {.Int16 = a}.UInt16
End Function
<Extension()> Public Function ToSigned(a As UInt32) As Int32
Return New NumberUnion With {.UInt32 = a}.Int32
End Function
<Extension()> Public Function ToUnsigned(a As Int32) As UInt32
Return New NumberUnion With {.Int32 = a}.UInt32
End Function
<Extension()> Public Function ToSigned(a As UInt64) As Int64
Return New NumberUnion With {.UInt64 = a}.Int64
End Function
<Extension()> Public Function ToUnsigned(a As Int64) As UInt64
Return New NumberUnion With {.Int64 = a}.UInt64
End Function
End Module
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment