C type unions in VB RRS feed

  • Question

  • In the application I am developing, I use single precision reals.  these are stored in the 32 bit IEEE format.  I then need to send these reals via RS-232, so they must be broken down into bytes.  In C I would just make the variable a union of float and unsigned short (see my c code below).  Can this be done in VB?


    union float_tag
      float fval;
      unsigned short ival;

    unsigned char ByteToSend;

    unsigned short FloatStoredAsUint;




      int j;


      X.fval = 2.3345;

      FloatStoredAsUint = X.ival;



        ByteToSend = FloatStoredAsUint & 0xFF;

        SendByteOverRS232(ByteToSend);       //ficticous procedure for sending bytes out over RS232

        FloatStoredAsUint => 8;



    Wednesday, March 5, 2008 3:49 PM


  • Like this;

    Code Snippet
    <StructLayout(LayoutKind.Explicit)> _
    Private Structure Thingy
        <FieldOffset(0)> _
    Public fVal As Single
        <FieldOffset(0)> _
    Public iVal As UInteger
    End Structure


    Code Snippet
    Dim thingy1 As Thingy
    thingy1.fVal =
    Dim floatStoredAsUInt As UInteger = thingy1.iVal
    For i As Integer = 0 To 3
    Dim byteToSend As Byte = floatStoredAsUInt And &HFF
        floatStoredAsUInt = floatStoredAsUInt >> 8

    But it is easier to use the BitConverter class:

    Code Snippet
    Dim s As Single = CSng(rand.NextDouble)
    For Each b As Byte In BitConverter.GetBytes(s)

    (If the results aren't right, then incorrect endianness would be the first thing to check.).

    Edit: StructLayout needs an import: System.Runtime.InteropServices

    Wednesday, March 5, 2008 5:23 PM