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.

4
  • have you tried Arrays.toString(byte[] ) for converting byte to string? Commented Dec 22, 2015 at 15:36
  • x += Integer.toBinaryString(b); would be x += "1000101"; for character 'E' (=ascii 69) Commented Dec 22, 2015 at 15:47
  • @JörnBuitink yes, but how I reconvert that binary string into the original string "Example"? Commented Dec 22, 2015 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 Commented Dec 22, 2015 at 16:32

1 Answer 1

-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);
Sign up to request clarification or add additional context in comments.

6 Comments

Nope. I said I'm supposing to do something with that byte[] array so I can't delete that middle section.
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.
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.
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.
Could you post some code example? I would be very grateful!
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.