A shorter example
private static final Charset UTF_8 = Charset.forName("UTF-8");
String text = "Hello World!";
byte[] bytes = text.getBytes(UTF_8);
System.out.println("bytes= "+Arrays.toString(bytes));
System.out.println("text again= "+new String(bytes, UTF_8));
prints
bytes= [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]
text again= Hello World!
import java.lang.*;
import java.io.*;
class d2b
{
public static void main(String args[]) throws IOException{
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the decimal value:");
String h = b.readLine();
int k = Integer.parseInt(h);
String out = Integer.toBinaryString(k);
System.out.println("Binary: " + out);
}
}
The usual way is to use String#getBytes()
to get the underlying bytes and then present those bytes in some other form (hex, binary whatever).
Note that getBytes()
uses the default charset, so if you want the string converted to some specific character encoding, you should use getBytes(String encoding)
instead, but many times (esp when dealing with ASCII) getBytes()
is enough (and has the advantage of not throwing a checked exception).
For specific conversion to binary, here is an example:
String s = "foo";
byte[] bytes = s.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("'" + s + "' to binary: " + binary);
Running this example will yield:
'foo' to binary: 01100110 01101111 01101111
Here are my solutions. Their advantages are : easy-understanding code, works for all characters. Enjoy.
Solution 1 :
public static void main(String[] args) {
String str = "CC%";
String result = "";
char[] messChar = str.toCharArray();
for (int i = 0; i < messChar.length; i++) {
result += Integer.toBinaryString(messChar[i]) + " ";
}
System.out.println(result);
}
prints :
1000011 1000011 100101
Solution 2 :
Possibility to choose the number of displayed bits per char.
public static String toBinary(String str, int bits) {
String result = "";
String tmpStr;
int tmpInt;
char[] messChar = str.toCharArray();
for (int i = 0; i < messChar.length; i++) {
tmpStr = Integer.toBinaryString(messChar[i]);
tmpInt = tmpStr.length();
if(tmpInt != bits) {
tmpInt = bits - tmpInt;
if (tmpInt == bits) {
result += tmpStr;
} else if (tmpInt > 0) {
for (int j = 0; j < tmpInt; j++) {
result += "0";
}
result += tmpStr;
} else {
System.err.println("argument 'bits' is too small");
}
} else {
result += tmpStr;
}
result += " "; // separator
}
return result;
}
public static void main(String args[]) {
System.out.println(toBinary("CC%", 8));
}
prints :
01000011 01000011 00100101
While playing around with the answers I found here to become familiar with it I twisted Nuoji's solution a bit so that I could understand it faster when looking at it in the future.
public static String stringToBinary(String str, boolean pad ) {
byte[] bytes = str.getBytes();
StringBuilder binary = new StringBuilder();
for (byte b : bytes)
{
binary.append(Integer.toBinaryString((int) b));
if(pad) { binary.append(' '); }
}
return binary.toString();
}
A String
in Java can be converted to "binary" with its getBytes(Charset)
method.
byte[] encoded = "????????!".getBytes(StandardCharsets.UTF_8);
The argument to this method is a "character-encoding"; this is a standardized mapping between a character and a sequence of bytes. Often, each character is encoded to a single byte, but there aren't enough unique byte values to represent every character in every language. Other encodings use multiple bytes, so they can handle a wider range of characters.
Usually, the encoding to use will be specified by some standard or protocol that you are implementing. If you are creating your own interface, and have the freedom to choose, "UTF-8" is an easy, safe, and widely supported encoding.
This is my implementation.
public class Test {
public String toBinary(String text) {
StringBuilder sb = new StringBuilder();
for (char character : text.toCharArray()) {
sb.append(Integer.toBinaryString(character) + "\n");
}
return sb.toString();
}
}
public class HexadecimalToBinaryAndLong{
public static void main(String[] args) throws IOException{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the hexa value!");
String hex = bf.readLine();
int i = Integer.parseInt(hex); //hex to decimal
String by = Integer.toBinaryString(i); //decimal to binary
System.out.println("This is Binary: " + by);
}
}
You can also do this with the ol' good method :
String inputLine = "test123";
String translatedString = null;
char[] stringArray = inputLine.toCharArray();
for(int i=0;i<stringArray.length;i++){
translatedString += Integer.toBinaryString((int) stringArray[i]);
}
int no=44;
String bNo=Integer.toString(no,2);//binary output 101100
String oNo=Integer.toString(no,8);//Oct output 54
String hNo=Integer.toString(no,16);//Hex output 2C
String bNo1= Integer.toBinaryString(no);//binary output 101100
String oNo1=Integer.toOctalString(no);//Oct output 54
String hNo1=Integer.toHexString(no);//Hex output 2C
String sBNo="101100";
no=Integer.parseInt(sBNo,2);//binary to int output 44
String sONo="54";
no=Integer.parseInt(sONo,8);//oct to int output 44
String sHNo="2C";
no=Integer.parseInt(sHNo,16);//hex to int output 44
Source: Stackoverflow.com