KingFish
KingFish

Reputation: 9163

Converting 32 byte array to 32 bit string

I have the following code. I have a 32 length string which is converted to a byte array. Problem is I need to convert it to a 32 length string. Problem is, it's coming back as a 64 length string. Is there some magic I should look at?

class Go {

    public void run() {
        String testString = "12345678901234567890123456789012";

        byte[] bytesData = testString.getBytes();
        StringBuilder st = new StringBuilder();

        for (byte b : bytesData) {
            st.append(String.format("%2d", b));
        }

        System.out.println(st.toString());
    }


    public static void main(String[] v2) {
        Go v = new Go();
        v.run();
    }
}

Upvotes: 1

Views: 2110

Answers (2)

mypetlion
mypetlion

Reputation: 2524

@azro gave you the right answer, but for the sake of education, I'll point out what you were doing wrong. When you get the byte value of a char in a string, you're getting the ascii value. So when you use String.format("%2d", b), you're getting the int value of the char itself, not the char that it represents. Instead, you could change your loop to something like this:

    for (byte b : bytesData) {
        st.append( (char)b );
    }

But again, use what @azro said. I'm only explaining how you could go about it if you were interested in how things work under the hood.

Upvotes: 2

azro
azro

Reputation: 54148

You use this String constructor : public String(byte[] bytes) (Oracle Doc)

String testString = "12345678901234567890123456789012";
System.out.println(testString);                          //12345678901234567890123456789012

byte[] bytesData = testString.getBytes();

String res = new String(bytesData);
System.out.println(res);                                 //12345678901234567890123456789012

Upvotes: 2

Related Questions