How to convert int to binary with leading zeros in Ruby

1 Answer

0 votes
# A function that converts an integer to a binary string with leading zeros.
# - num: The integer value to convert.
# - bits: The target bit width (e.g., 8, 16, 32) determining the leading zeros.
def int_to_binary(num, bits)
  # The format specifier breakdown:
  # - '0' specifies zero-padding instead of spaces
  # - '*' dynamically takes the width argument (bits)
  # - 'b' formats the integer as binary (base 2)
  format("%0*b", bits, num)
end

# Complete program execution
if __FILE__ == $0
  # Define the data provided
  num = 153

  # 1. Convert to an 8-bit binary representation (153 fits within 8 bits: 0 to 255)
  bin_str_8 = int_to_binary(num, 8)

  # 2. Convert to a 16-bit binary representation to demonstrate wider padding
  bin_str_16 = int_to_binary(num, 16)

  # Display the results
  puts "Original Integer: #{num}"
  puts "Binary (8-bit)  : #{bin_str_8}"
  puts "Binary (16-bit) : #{bin_str_16}"
end


# run:
#
# Original Integer: 153
# Binary (8-bit)  : 10011001
# Binary (16-bit) : 0000000010011001
#

 



answered 1 day ago by avibootz
...