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