How do I convert a String written as Binary, to binary (in byte array)?
If I have a String:
String binary = "0000"
I want the binary data to be 0000
.
below is what happens when I set the binary to a byte array (which in turn returns 48, which is ASCII)
Binary String: 0000
Binary Byte array: 48
Binary Byte array: 48
Binary Byte array: 48
Binary Byte array: 48
I'm not good at explaining so hopefully the above example was enough to tell you what I want.
EDIT: This is to set the data into a binary file.
-
possible duplicate of Convert Java String to byte[] arrayPM 77-1– PM 77-12014年07月21日 23:10:35 +00:00Commented Jul 21, 2014 at 23:10
-
At least @Braj knows what Im talking about. PM 77-1 This is in no possible way a duplicate of Coverting a Java String to a byte[] array. Im aware of how to do that, Im NOT aware however, of how to put the actual input string value and set it as binary.AMDG– AMDG2014年07月21日 23:12:39 +00:00Commented Jul 21, 2014 at 23:12
-
OK I got it your point. Let me update it.Braj– Braj2014年07月21日 23:14:07 +00:00Commented Jul 21, 2014 at 23:14
-
@LinkTheProgrammer - You seem to be confused about different represenations of a value.PM 77-1– PM 77-12014年07月21日 23:19:26 +00:00Commented Jul 21, 2014 at 23:19
-
You have to mention that you want decimal value from binary.Braj– Braj2014年07月21日 23:23:00 +00:00Commented Jul 21, 2014 at 23:23
4 Answers 4
Use this:
System.out.println(Integer.toBinaryString(Integer.parseInt("000",2))); // gives 0
System.out.println(Integer.toBinaryString(Integer.parseInt("010",2))); // gives 10
System.out.println(Integer.toBinaryString(Integer.parseInt("100",2))); // gives 100
3 Comments
Maybe you want this:
int i = Integer.valueOf(binary, 2); // ie base 2
This call expects the input to be a string of 0 and 1 chars.
Then if you want an array of bytes:
byte[] bytes = new ByteBuffer().putInt(i).compact().array();
13 Comments
Convert into Decimal from Binary
System.out.println(new BigInteger("1010",2).toString()); // 10 decimal
Convert into Binary/Octal/Hex from Decimal
You can use BigInteger#toString(radix) method to get value in any radix.
System.out.println(new BigInteger("10").toString(2)); // 1010 binary
System.out.println(new BigInteger("10").toString(8)); // 12 octal
System.out.println(new BigInteger("10").toString(16)); // a hexadecimal
Let me explain you a bit more how it works with different base
(10)10 = (1010)2
(10)10 = (12)8
(10)10 = (a)16
4 Comments
System.out.println(newBigInteger(int radix).toString(2));
however this is a String input that I want to write as text and then put into a new binary file. Not something confusing for the consumer of the software I want to make.JBBP framework has in utils a special method to convert a string contains a binary defined data into byte array
byte [] converted = JBBPUtils.str2bin("00000000");