=begin
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
...
=end
def split_bytes(n)
[
n & 0xFF, # lowest byte
(n >> 8) & 0xFF,
(n >> 16) & 0xFF,
(n >> 24) & 0xFF # highest byte
]
end
=begin
print_bits(label, value)
------------------------
Prints an 8-bit or 32-bit value in binary.
Uses value.to_s(2) and manual zero-padding.
=end
def print_bits(label, value, bits)
binary = value.to_s(2)
# Pad with leading zeros
if binary.length < bits
binary = "0" * (bits - binary.length) + binary
end
puts "#{label} (#{bits} bits): #{binary}"
end
def main
value = 3298312
bytes = split_bytes(value)
puts "Bytes (little-endian order):"
bytes.each_with_index do |b, i|
puts "byte[#{i}]: #{b}"
end
puts "\nBit representation:"
# Print full 32-bit value
print_bits("Full value", value, 32)
# Print each byte in binary
bytes.each_with_index do |b, i|
print_bits("byte[#{i}]", b, 8)
end
end
main
=begin
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
=end