I would like to be able to convert a String (with words/letters) to other forms, like binary. How would I go about doing this. I am coding in BLUEJ (Java). Thanks
-
Please give an example of the inputs and outputs you're talking about. – S.Lott May 27 '09 at 18:03
-
What do you mean "other forms, like binary." Technically, the string is already in a binary representation. Do you mean that you want to take a string input and display the binary representation of the string, as it would be encoded in ASCII bytes? – Jared May 27 '09 at 18:05
-
for example entering testing123 and getting the binary equivalent as an output – May 27 '09 at 18:07
-
yes so having a readable string and convert it to binary (ones and zeros) – May 27 '09 at 18:09
-
4@Keith: Please do not add comments to your own question -- please update your question. Please provide an actual example of the output you'd like to see. – S.Lott May 27 '09 at 18:22
10 Answers
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

- 3,438
- 2
- 21
- 35
-
Nuoji, Can you please guide me to some study material(s) which shall help me in building the understanding of the complete solution. Example why the "ANDING" and left shift etc. Thanks in advance – Sameer Patil Jul 11 '12 at 08:56
-
4Just read up on wikipedia http://en.wikipedia.org/wiki/Bitwise_operation other than that. What the code does is to see if the highest bit is set or not. If it is, then add a one, otherwise add a zero. Then I move all bits on the original number to the left, which means the next highest bit is now at the position of the highest bit, next-next highest at the next highest etc, and the previous highest bit is gone. Again I test if the highest bit is set (this was originally the next highest bit) and append '0' or '1'. Then move the bits one step and do the same thing until you tested all bits. – Nuoji Jul 15 '12 at 20:56
-
-
I habitually treat the loops as if they were written: `for (final byte b : bytes)`. Since I did not add `final`, creating a temp is not strictly necessary. @Babbleshack – Nuoji Aug 29 '14 at 11:36
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!

- 525,659
- 79
- 751
- 1,130
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.
- It's easy, because rather than including some way to note the encoding of each message, you can default to UTF-8.
- It's safe, because UTF-8 can encode any character that can be used in a Java character string.
- It's widely supported, because it is one of a small handful of character encodings that is required to be present in any Java implementation, all the way down to J2ME. Most other platforms support it too, and it's used as a default in standards like XML.

- 265,237
- 58
- 395
- 493
-
i tried that but it says i am not controlling the exception my current code is... public class convertStringToACHII { public void convert(String word) { String s = word; byte[] b = s.getBytes("UTF-8"); System.out.println("In UTF-8: " + b); byte[] c = s.getBytes("US-ASCII"); System.out.println("In ASCII: " + c); } } – May 27 '09 at 18:06
-
2s.getBytes("UTF-8") throws UnsupportedEncodingException. So you need to surround your conversion with a try-catch if you are using getBytes(String encoding). – Nuoji May 27 '09 at 18:08
-
1Yes, because you can specify any encoding, and some encoding are optional, this method can throw a (checked) exception. Then if the code runs in a JVM without a particular encoding, you can detect it. However, UTF-8 is required, so I think it is fair to wrap this exception like this: new IllegalStateException("Required encoding not available: UTF-8", ex); – erickson May 27 '09 at 18:11
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

- 71
- 1
- 3
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

- 1,033
- 10
- 11
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();
}
}

- 42
- 4
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();
}

- 11
- 1
-
1I would be great if you could edit your question and share your understanding. For example, you could explain what your solution does better so that it is easier to understand. – honk Dec 03 '14 at 19:39
-
1Don't use `String.getBytes()`. It will use whatever the default platform encoding is, which is pretty much random. So depending on where you run the code it will produce a different result. – Christoffer Hammarström Jun 03 '15 at 13:39
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);
}
}
-
3welcome to Stack Overflow; indent code 4 spaces (or use the toolbar button to do the same) – McDowell Dec 18 '10 at 11:47
-
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]);
}

- 437
- 1
- 4
- 14
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);
}
}
-
1in this code we can directly convert hexa decimal code into decimal valu and binary value at a time – siva Sep 06 '10 at 10:16
-
1