0

I'm dealing with some code that converts a String into a byte[], then from byte[] to String (a String which is a binary representation of the original String), then I'm supposing to do something with that String.
When I try to convert the String to byte[] and byte[] to the original String, something is not working.

        byte[] binary = "Example".getBytes(StandardCharsets.UTF_8);
        String x = new String();
        for(byte b : binary)
        {
                x += Integer.toBinaryString(b);
        }
        byte[] b = new byte[x.length()];
        for (int i = 0; i < b.length; i++) 
        {
            b[i] = (byte) (x.charAt(i) - '0');
        }
        String str = new String(b, StandardCharsets.UTF_8);
        System.out.println(str);

As you can see in that code, I'm using an example String called "Example" and I'm trying to do what I wrote above.
When I print str, I'm not getting that "Example" string.
Does anyone know a way to do this? I searched for a solution on Stack Overflow itself, but I can't figure out a solution.

cbay
  • 72
  • 7
Omar93
  • 45
  • 6
  • have you tried Arrays.toString(byte[] ) for converting byte to string? – Shriram Dec 22 '15 at 15:36
  • `x += Integer.toBinaryString(b);` would be `x += "1000101"; ` for character 'E' (=ascii 69) – Jörn Buitink Dec 22 '15 at 15:47
  • @JörnBuitink yes, but how I reconvert that binary string into the original string "Example"? – Omar93 Dec 22 '15 at 16:28
  • That's the crucial point: I have a binary string (example "100101" for character "E", as you said) and I have to display back "E" using that binary string – Omar93 Dec 22 '15 at 16:32

1 Answers1

-1

This should work without the middle section.

byte[] binary = "Example".getBytes(StandardCharsets.UTF_8);
String str = new String(binary, StandardCharsets.UTF_8);
System.out.println(str);
dolan
  • 1,716
  • 11
  • 22
  • Nope. I said I'm supposing to do something with that byte[] array so I can't delete that middle section. – Omar93 Dec 22 '15 at 16:34
  • Well then the real question is what are you trying to do with it? Because that mutation operation is what's causing the string to change. – dolan Dec 22 '15 at 16:40
  • I'm implementing something like a cipher, so I have to do something with the binary representation of the string and then obtain again the binary representation of the string so I can obtain the original string. – Omar93 Dec 22 '15 at 16:52
  • Oh. Now I get it. You are converting a string -> byte[] -> string of 1s and 0s -> byte[] where each element is a bit of the 1s and 0s string -> string. You will need to use bit shifting to get that second byte[] to be bytes instead of just bits if you want to convert it back to a string. – dolan Dec 22 '15 at 17:03
  • Could you post some code example? I would be very grateful! – Omar93 Dec 22 '15 at 17:05
  • I think I finally get it! Here's the code: [http://pastebin.com/2WcQfjip](http://pastebin.com/2WcQfjip) – Omar93 Dec 22 '15 at 17:27