Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String to binary output in Java

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!

like image 721
Nick Avatar asked Nov 13 '10 18:11

Nick


People also ask

How is a string converted to binary?

To convert a string to binary, we first append the string's individual ASCII values to a list ( l ) using the ord(_string) function. This function gives the ASCII value of the string (i.e., ord(H) = 72 , ord(e) = 101). Then, from the list of ASCII values we can convert them to binary using bin(_integer) .

How do you return a binary number in Java?

toBinaryString() method returns a string representation of the integer argument as an unsigned integer in base 2. It accepts an argument in Int data-type and returns the corresponding binary string.

What is toInt in Java?

toInt() is a static method of the NumberUtils class that is used to convert the given string to an integer value. One variant of the method accepts a default value that is returned if the conversion fails.


2 Answers

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;
like image 199
stacker Avatar answered Oct 04 '22 14:10

stacker


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.

like image 27
Andrzej Doyle Avatar answered Oct 04 '22 13:10

Andrzej Doyle