Returns a String of 1's and 0's of length 8 that represents the binary representation of the character. - Java java.lang

Java examples for java.lang:char

Description

Returns a String of 1's and 0's of length 8 that represents the binary representation of the character.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        char c = 'a';
        System.out.println(binaryAsciiCodeFromChar(c));
    }//  w w  w .  j  a  v a 2  s .  c o m

    /**
     * Returns a String of 1's and 0's of length 8 that represents the binary representation of the
     * character. Assumes that input character is an ASCII character.
     */
    public static String binaryAsciiCodeFromChar(char c) {
        String tail = Integer.toBinaryString(c & 0xFF).replace(' ', '0');
        int tailLen = tail.length();
        for (int i = 0; i < 8 - tailLen; i++) {
            tail = "0".concat(tail);
        }
        return tail;
    }
}

Related Tutorials