How to print the bits of a character in Scala

2 Answers

0 votes
object CharacterBitsProgram {
 
  /**
   * Converts a character to its 8-bit binary representation.
   *
   * @param ch The character to convert.
   * @return An 8-bit binary string.
   */
  def charToBits(ch: Char): String = {
    val value: Int = ch.toInt
 
    // Convert to binary and pad with leading zeros.
    String.format("%8s", Integer.toBinaryString(value)).replace(' ', '0')
  }
 
  /**
   * Prints a character and its binary representation.
   *
   * @param ch The character to display.
   */
  def printCharacterBits(ch: Char): Unit = {
    val bits: String = charToBits(ch)
 
    println(s"Character: '$ch'")
    println(s"Decimal  : ${ch.toInt}")
    println(s"Binary   : $bits")
  }
 
  def main(args: Array[String]): Unit = {
 
    // Usage examples
 
    printCharacterBits('A')
    println()
 
    printCharacterBits('a')
    println()
 
    printCharacterBits('5')
    println()
 
    printCharacterBits('@')
  }
}
 
 
 
/*
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
object CharacterBitsProgram {

  /**
   * Converts a character to a 16-bit binary string.
   */
  def charTo16Bits(ch: Char): String = {
     // Scala Char is a 16-bit Unicode character (UTF-16 code unit). 
     // To display all 16 bits:
     String.format("%16s", Integer.toBinaryString(ch.toInt)).replace(' ', '0')
  }

  def main(args: Array[String]): Unit = {

    println(charTo16Bits('A'))
  }
}


/*
run:

0000000001000001

*/

 



answered Oct 16 by avibootz
...