Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,236 questions

56,139 answers

573 users

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

1 Answer

0 votes
#include <stdio.h>
#include <stdint.h>

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

void split_bytes(uint32_t n, uint8_t bytes[4]) {
    bytes[0] = (uint8_t)(n & 0xFF);         // lowest byte
    bytes[1] = (uint8_t)((n >> 8) & 0xFF);
    bytes[2] = (uint8_t)((n >> 16) & 0xFF);
    bytes[3] = (uint8_t)((n >> 24) & 0xFF); // highest byte
}

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

    This uses a simple loop instead of std::bitset.
*/
void print_bits(const char *label, uint32_t value, size_t bits) {
    printf("%s (%zu bits): ", label, bits);

    for (size_t i = 0; i < bits; ++i) {
        uint32_t mask = 1u << (bits - 1 - i);
        putchar((value & mask) ? '1' : '0');
    }

    putchar('\n');
}

int main(void) {
    uint32_t value = 3298312;

    uint8_t bytes[4];
    split_bytes(value, bytes);

    printf("Bytes (little-endian order):\n");
    for (size_t i = 0; i < 4; ++i) {
        printf("byte[%zu]: %u\n", i, (unsigned)bytes[i]);
    }

    printf("\nBit representation:\n");

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

    // Print each byte in binary
    for (size_t i = 0; i < 4; ++i) {
        char label[32];
        snprintf(label, sizeof(label), "byte[%zu]", i);
        print_bits(label, bytes[i], 8);
    }

    return 0;
}


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