How to print the bits of a character in Kotlin

3 Answers

0 votes
/**
 * Converts a character to a 16-bit binary string.
 */
fun charTo16Bits(ch: Char): String {
    // A Kotlin Char is a 16-bit Unicode UTF-16 code unit. 
    // To display all 16 bits stored in the character:
    return ch.code.toString(2).padStart(16, '0')
}

fun main() {

   // Usage examples

   println(charTo16Bits('A'))
}


/*
run:

0000000001000001

*/

 



answered Oct 16 by avibootz
0 votes
// Kotlin's standard library 
fun charToBits(ch: Char): String =
    ch.code.toString(2).padStart(8, '0')

fun main() {

   // Usage examples

   println(charToBits('A'))
}


/*
run:

01000001

*/

 



answered Oct 16 by avibootz
0 votes
/**
 * Converts a character to its 8-bit binary representation.
 *
 * Note:
 * This function is intended for ASCII characters.
 * Kotlin Char values are Unicode characters, so see the
 * Unicode example below for a full 16-bit representation.
 *
 * @param ch The character to convert.
 * @return An 8-bit binary string.
 */
fun charToBits(ch: Char): String {
    val value: Int = ch.code

    return value.toString(radix = 2).padStart(8, '0')
}

/**
 * Prints a character and its binary representation.
 *
 * @param ch The character to display.
 */
fun printCharacterBits(ch: Char) {
    val bits: String = charToBits(ch)

    println("Character: '$ch'")
    println("Decimal  : ${ch.code}")
    println("Binary   : $bits")
}

fun main() {

    // 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
...