#include <iostream>
#include <cstdint>
#include <array>
#include <bitset>
/*
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
...
*/
std::array<std::uint8_t, 4> split_bytes(std::uint32_t n) {
return {
static_cast<std::uint8_t>(n & 0xFF), // lowest byte
static_cast<std::uint8_t>((n >> 8) & 0xFF),
static_cast<std::uint8_t>((n >> 16) & 0xFF),
static_cast<std::uint8_t>((n >> 24) & 0xFF) // highest byte
};
}
/*
print_bits(label, value)
------------------------
Prints an 8-bit or 32-bit value in binary using std::bitset.
*/
template <typename T>
void print_bits(const std::string& label, T value) {
constexpr size_t bits = sizeof(T) * 8;
std::cout << label << " (" << bits << " bits): "
<< std::bitset<bits>(value) << "\n";
}
int main() {
std::uint32_t value = 3298312;
auto bytes = split_bytes(value);
std::cout << "Bytes (little-endian order):\n";
for (size_t i = 0; i < bytes.size(); ++i) {
std::cout << "byte[" << i << "]: "
<< static_cast<unsigned>(bytes[i]) << "\n";
}
std::cout << "\nBit representation:\n";
// Print full 32-bit value
print_bits("Full value", value);
// Print each byte in binary
for (size_t i = 0; i < bytes.size(); ++i) {
print_bits("byte[" + std::to_string(i) + "]", bytes[i]);
}
}
/*
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
*/