Convert Text to Binary in Java

In this example, We will show you sample program about, How to Convert Text to Binary in Java programming language. The example were tested and shared in the same post.

Exmple Program

package com.dineshkrish;
/**
* 
* @author Dinesh Krishnan
*
*/
public class TextToBinary {
public static void main(String[] args) {
String str = "dinesh krishnan";
byte[] bytes = str.getBytes();
StringBuilder binary = new StringBuilder();
for (byte b : bytes) {
int val = b;
for (int i = 0; i < 8; i++) {
binary.append((val & 128) == 0 ? 0 : 1);
val <<= 1;
}
binary.append(' ');
}
System.out.println("'" + str + "' to binary: " + binary);
}
}

Output

'dinesh krishnan' to binary: 01100100 01101001 01101110 01100101 
01110011 01101000 00100000 01101011 
01110010 01101001 01110011 01101000 
01101110 01100001 01101110 

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *