How to print the bits of a character in Java

2 Answers

0 votes
class Program {
    public static void main(String[] args) {
        char ch = 'a';
         
        System.out.println(Integer.toBinaryString(ch));
    }
}
 
 
 
/*
run:
  
1100001
   
*/

 



answered Mar 5, 2019 by avibootz
edited Oct 16 by avibootz
0 votes
/**
 * Demonstrates how to print the bits of a character.
 */
public final class CharacterBitsDemo {

    /**
     * Prevent instantiation of utility class.
     */
    private CharacterBitsDemo() {
    }

    public static void main(String[] args) {

        // Usage examples
        printCharacterBits('A');
        System.out.println();

        printCharacterBits('a');
        System.out.println();

        printCharacterBits('5');
        System.out.println();

        printCharacterBits('@');
    }

    /**
     * Converts a character to its 8-bit binary representation.
     *
     * @param ch the character to convert
     * @return an 8-bit binary string
     */
    public static String charToBits(char ch) {
        int value = ch;

        // Convert to binary and pad with leading zeros.
        return String.format("%8s", Integer.toBinaryString(value))
                     .replace(' ', '0');
    }

    /**
     * Prints a character and its binary representation.
     *
     * @param ch the character to display
     */
    public static void printCharacterBits(char ch) {
        System.out.println("Character: '" + ch + "'");
        System.out.println("Decimal  : " + (int) ch);
        System.out.println("Binary   : " + charToBits(ch));
    }
}


/*
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 Mar 5, 2019 by avibootz
edited Oct 16 by avibootz
...