String to binary output in Java
60,573
Solution 1
Only Integer has a method to convert to binary string representation check this out:
import java.io.UnsupportedEncodingException;
public class TestBin {
public static void main(String[] args) throws UnsupportedEncodingException {
byte[] infoBin = null;
infoBin = "this is plain text".getBytes("UTF-8");
for (byte b : infoBin) {
System.out.println("c:" + (char) b + "-> "
+ Integer.toBinaryString(b));
}
}
}
would print:
c:t-> 1110100
c:h-> 1101000
c:i-> 1101001
c:s-> 1110011
c: -> 100000
c:i-> 1101001
c:s-> 1110011
c: -> 100000
c:p-> 1110000
c:l-> 1101100
c:a-> 1100001
c:i-> 1101001
c:n-> 1101110
c: -> 100000
c:t-> 1110100
c:e-> 1100101
c:x-> 1111000
c:t-> 1110100
Padding:
String bin = Integer.toBinaryString(b);
if ( bin.length() < 8 )
bin = "0" + bin;
Solution 2
Arrays do not have a sensible toString
override, so they use the default object notation.
Change your last line to
return Arrays.toString(infoBin);
and you'll get the expected output.
![Nick](https://i.stack.imgur.com/bbc8H.jpg?s=256&g=1)
Author by
Nick
Updated on August 27, 2020Comments
-
Nick almost 4 years
I want to get binary (011001..) from a String but instead i get [B@addbf1 , there must be an easy transformation to do this but I don't see it.
public static String toBin(String info){ byte[] infoBin = null; try { infoBin = info.getBytes( "UTF-8" ); System.out.println("infoBin: "+infoBin); } catch (Exception e){ System.out.println(e.toString()); } return infoBin.toString(); }
Here i get infoBin: [B@addbf1
and I would like infoBin: 01001...Any help would be appreciated, thanks!
-
Nick over 13 yearsHi Andrzej, your answer makes a lot of sense but I get [84, 104, 105, 115, 32, 105, 115, 32, 97, 32,..] instead of (01101010...) any suggestions? thank you
-
stacker over 13 yearsmaybe you need some padding for your bytes
-
Nick over 13 yearsThank you very much for your help!
-
Nick over 13 years@stacker why is the space endoded on only 6 digits and not 7? (ex: c: -> 100000)
-
Nick over 13 yearsshould I manualy add a 0 at the begining? (ex: (ex: c: -> 0100000) )
-
stacker over 13 years@Nick that's what I meant whith my first comment, leading zeros are omitted so you need to
-
stacker over 13 years@Nick that's what I meant whith my first comment, leading zeros are omitted so you need to add them as you already noticed. Or you write a method which adapt the behaviour Integer.toBinaryString(). If it is not critical I would suggest to pad the strings with leading '0's.
-
Nick over 13 years@stacker how can I make it work for a byte that starts with "1" ? If I do it on a byte that starts with "0", I get 8 chars, as expected. If I do it on a byte that starts with "1", I get 32 chars instead.
-
stacker over 13 years@Nick check String.length() and use substring(0,8) (not tested)
-
Pippi over 8 yearsSorry!! If i would like get binary of "%" (it's 00100101) in this way i will receive "0" + "100101" and not "00100101".