What kind of algorithm/method would you use to change a simple string to binary and vice-versa (In Java)?
Asked
Active
Viewed 196 times
-1
-
2Pls share more about problem definition. Also provide sample input – Dark Knight Feb 17 '14 at 14:44
-
Changing "Hello" to Binary (01001000 01100101 01101100 01101100 01101111). – MrLolEthan Feb 17 '14 at 14:54
-
A "simple String" is already binary, what else? What do you want? – Ingo Feb 17 '14 at 15:01
3 Answers
2
str.getBytes()
returns byte array,
String(byte[], java.lang.String)
creates new String instance from byte array an charset.
I hope this helps...

AlexR
- 114,158
- 16
- 130
- 208
0
You can use BigInteger to convert it to Hex and back.
byte [] binary = new byte[] {0,1,2,3,4,5};
System.out.println("Binary: "+Arrays.toString(binary));
String asText = new BigInteger(binary).toString(16);
System.out.println("Text: "+asText);
byte[] asBinary = new BigInteger(asText, 16).toByteArray();
System.out.println("Back to Binary: "+Arrays.toString(asBinary));
prints:
Binary: [0, 1, 2, 3, 4, 5]
Text: 102030405
Back to Binary: [1, 2, 3, 4, 5]

OldCurmudgeon
- 64,482
- 16
- 119
- 213