How to combine two 32-bit values into one 64-bit value in Ruby

1 Answer

0 votes
#
# Combine two 32‑bit unsigned integers into one 64‑bit unsigned integer.
#
# Ruby integers are arbitrary‑precision, but we can still treat them
# as fixed‑width values using bit operations.
#

# Function that combines two 32‑bit integers into a 64‑bit integer.
#
# Explanation:
# - Convert both inputs to Integer (Ruby already handles big ints).
# - Shift the high part left by 32 bits to place it in the upper half.
# - OR the low part into the lower 32 bits.
def combine_two_32bit(high, low)
  (high << 32) | low
end

# Function that prints a 64‑bit value in uppercase hexadecimal
# with leading zeros.
def print_hex64(value)
  puts "0x%016X" % value
end

# Example usage
high = 0x11223344  # Example high 32 bits
low  = 0x55667788  # Example low 32 bits

combined = combine_two_32bit(high, low)

puts "High 32 bits: 0x%08X" % high
puts "Low  32 bits: 0x%08X" % low

print "Combined 64-bit value: "
print_hex64(combined)



=begin
run:

High 32 bits: 0x11223344
Low  32 bits: 0x55667788
Combined 64-bit value: 0x1122334455667788

=end

 



answered 8 hours ago by avibootz

Related questions

...