leviathan11
leviathan11

Reputation: 21

Convert byte array to a String

I'm trying to convert a byte array to a String and writing it to a file using PrintWriter (only to check it's value with mc, i need the content in String) My problem summed up:

//-77 is "equivalent" to 179 or 0xb3 (i also tried those using ByteArrayOutputStream, where these are valid values)
byte[] b = new byte[]{0,0,1,-77};

//I save the String to a txt, so i can check its value with midnight commander
try(  PrintWriter out = new PrintWriter("~/Desktop/output.txt")){
    out.println( new String(b) );
}

The output.txt's content as hex with mc: 00 00 01 EF | BF BD 0A
Despite it should be: 00 00 01 B3

What causes this? I guess it's the encoding, but I don't know what type of encoding should I use (i tried some Cp### types, but none of them works so far).

UPDATE:
Every negative byte converted to String like this will result: EF BF BD
So it only works if the unsigned byte value is less than 128. So the question is how can i represent a byte greater than 127 in String like i did with 0-127 bytes?

Upvotes: 0

Views: 354

Answers (1)

Davide Spataro
Davide Spataro

Reputation: 7482

This will do the trick. It will output 00 00 01 b3 as expected.

FileOutputStream fos = new FileOutputStream("filename");
fos.write(b);
fos.close();

Upvotes: 2

Related Questions