Tech Off Post

Single Post Permalink

View Thread: Converting bits and bytes
  • User profile image
    RichardRudek

    This works for me:

        Dim data(0) As Int32
    data(0) = &HA0311A80
    Dim myBits As New BitArray(data)
    Dim myBytes(((myBits.Length + 7) \ 8) - 1) As Byte 'Use Integer Division ; zero-based.
    myBits.CopyTo(myBytes, 0)

    Dim s As String, t As String
    For Each d As Byte In myBytes
    s = s & Hex(d) & " "
    Dim a(0) As Byte
    a(0) = d
    Dim ba As New BitArray(a)
    For Each b As Boolean In ba
    t = CStr(IIf(b, "1", "0")) & t
    Next
    t = " " & t
    Next
    s = s & t

    The console output being:

    80 1A 31 A0  10100000 00110001 00011010 10000000

    One to note is that the binary to string converstion required me to build from right to left (classical/numerical style), which is the way I write my binary numbers. Others, though, may prefer them to be written with their least signicant bit on the left  - left to right style.