How to split a 32‑bit integer into its four bytes in Go

1 Answer

0 votes
package main

import (
    "fmt"
)

/*
    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 & 0xFF        → extract lowest byte
        (n >> 8) & 0xFF → extract next byte
        ...
*/

func split_bytes(n uint32) [4]byte {
    return [4]byte{
        byte(n & 0xFF),          // lowest byte
        byte((n >> 8) & 0xFF),
        byte((n >> 16) & 0xFF),
        byte((n >> 24) & 0xFF),  // highest byte
    }
}

/*
    print_bits(label, value)
    ------------------------
    Prints an 8-bit or 32-bit value in binary.

    Uses fmt.Sprintf("%08b") and manual padding for 32 bits.
*/
func print_bits(label string, value uint32, bits int) {
    var binary string

    if bits == 8 {
        binary = fmt.Sprintf("%08b", value)
    } else if bits == 32 {
        binary = fmt.Sprintf("%032b", value)
    }

    fmt.Printf("%s (%d bits): %s\n", label, bits, binary)
}

func main() {
    var value uint32 = 3298312

    bytes := split_bytes(value)

    fmt.Println("Bytes (little-endian order):")
    for i := 0; i < len(bytes); i++ {
        fmt.Printf("byte[%d]: %d\n", i, bytes[i])
    }

    fmt.Println("\nBit representation:")

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

    // Print each byte in binary
    for i := 0; i < len(bytes); i++ {
        print_bits(fmt.Sprintf("byte[%d]", i), uint32(bytes[i]), 8)
    }
}


/*
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
...