How to print the bits of a character in Ruby

3 Answers

0 votes
#
# Converts a single character to its 8-bit binary representation.
#
# @param char [String] A single character.
# @return [String] An 8-bit binary string.
# @raise [ArgumentError] If the input is not exactly one character.
#
def char_to_bits(char)
  raise ArgumentError, "Input must be exactly one character." unless char.is_a?(String) && char.length == 1

  # Get the character's numeric code point.
  code_point = char.ord

  # Convert to binary and pad with leading zeros.
  format("%08b", code_point)
end

#
# Prints a character and its binary representation.
#
# @param char [String] A single character.
#
def print_character_bits(char)
  bits = char_to_bits(char)

  puts "Character: '#{char}'"
  puts "Decimal  : #{char.ord}"
  puts "Binary   : #{bits}"
end

# ------------------------------------------------------------------
# Usage examples
# ------------------------------------------------------------------

begin
  print_character_bits("A")
  puts

  print_character_bits("a")
  puts

  print_character_bits("5")
  puts

  print_character_bits("@")
rescue ArgumentError => e
  warn "Error: #{e.message}"
end



# run:
#
# Character: 'A'
# Decimal  : 65
# Binary   : 01000001
# 
# Character: 'a'
# Decimal  : 97
# Binary   : 01100001
# 
# Character: '5'
# Decimal  : 53
# Binary   : 00110101
# 
# Character: '@'
# Decimal  : 64
# Binary   : 01000000
# 

 



answered Oct 16 by avibootz
edited Oct 16 by avibootz
0 votes
#
# Converts a single character to its 8-bit binary representation.
#

def unicode_char_to_bits(char)
  format("%b", char.ord)
end

puts unicode_char_to_bits("A")
puts unicode_char_to_bits("é")


# run:
#
# 1000001
# 11101001
# 

 



answered Oct 16 by avibootz
0 votes
#
# Converts a single character to its 8-bit binary representation.
#

def unicode_char_to_32_bits(char)
  format("%032b", char.ord)
end

puts unicode_char_to_32_bits("A")
puts unicode_char_to_32_bits("é")



# run:
#
# 00000000000000000000000001000001
# 00000000000000000000000011101001
# 

 



answered Oct 16 by avibootz
...