locked
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;
    }X;

    unsigned char ByteToSend;

    unsigned short FloatStoredAsUint;

     

    main()

    {

      int j;

     

      X.fval = 2.3345;

      FloatStoredAsUint = X.ival;

      for(j=0;j<4;j++)

      {

        ByteToSend = FloatStoredAsUint & 0xFF;

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

        FloatStoredAsUint => 8;

      }

    }

    Wednesday, March 5, 2008 3:49 PM

Answers

  • Like this;

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


    Then:

    Code Snippet
    Dim thingy1 As Thingy
    thingy1.fVal =
    CSng(rand.NextDouble)
    Dim floatStoredAsUInt As UInteger = thingy1.iVal
    For i As Integer = 0 To 3
        
    Dim byteToSend As Byte = floatStoredAsUInt And &HFF
        Debug.WriteLine(Hex(byteToSend))
        floatStoredAsUInt = floatStoredAsUInt >> 8
    Next


    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)
        Debug.WriteLine(Hex(b))
    Next



    (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