How to split a 32‑bit integer into its four bytes in VB.NET

1 Answer

0 votes
Imports System

Module SplitBytesProgram

    '
    '    split_bytes(n)
    '    --------------
    '    Splits a 32-bit unsigned integer into its four bytes.
    '
    '    Layout (little-endian order):
    '        byte(0) = lowest  8 bits
    '        byte(1) = next     8 bits
    '        byte(2) = next     8 bits
    '        byte(3) = highest  8 bits
    '
    '    Uses bitwise AND and shifts:
    '        n And &HFF        → extract lowest byte
    '        (n >> 8) And &HFF → extract next byte
    '        ...
    '
    Function split_bytes(n As UInteger) As Byte()
        Return New Byte() {
            CByte(n And &HFF),               ' lowest byte
            CByte((n >> 8) And &HFF),
            CByte((n >> 16) And &HFF),
            CByte((n >> 24) And &HFF)        ' highest byte
        }
    End Function

    '
    '    print_bits(label, value)
    '    ------------------------
    '    Prints an 8-bit or 32-bit value in binary.
    '
    '    Uses Convert.ToString(value, 2) and manual zero-padding.
    '
    Sub print_bits(lbl As String, value As UInteger, bits As Integer)
        Dim binary As String = Convert.ToString(value, 2)

        ' Pad with leading zeros
        If binary.Length < bits Then
            binary = New String("0"c, bits - binary.Length) & binary
        End If

        Console.WriteLine($"{lbl} ({bits} bits): {binary}")
    End Sub

    Sub Main()
        Dim value As UInteger = 3298312UI

        Dim bytes() As Byte = split_bytes(value)

        Console.WriteLine("Bytes (little-endian order):")
        For i As Integer = 0 To bytes.Length - 1
            Console.WriteLine($"byte[{i}]: {bytes(i)}")
        Next

        Console.WriteLine()
        Console.WriteLine("Bit representation:")

        ' Print full 32-bit value
        print_bits("Full value", value, 32)

        ' Print each byte in binary
        For i As Integer = 0 To bytes.Length - 1
            print_bits($"byte[{i}]", bytes(i), 8)
        Next
    End Sub

End Module


' run:
'
' Bytes (little-endian order):
' byte[0]: 8
' byte[1]: 84
' byte[2]: 50
' byte[3]: 0
'
' Bit representation:
' Full value (32 bits): 00000000001100100101010000001000
' byte[0] (8 bits): 00001000
' byte[1] (8 bits): 01010100
' byte[2] (8 bits): 00110010
' byte[3] (8 bits): 00000000
'

 



answered Jul 20 by avibootz
...