[java] Convert byte to string in Java

I use below code to convert byte to string:

System.out.println("string " + Byte.toString((byte)0x63));

Why it print "string 99". How to modify to let it print "string c"?

This question is related to java

The answer is


This is my version:

public String convertBytestoString(InputStream inputStream)
{
    int bytes;
    byte[] buffer = new byte[1024];

    bytes = inputStream.read(buffer);
    String stringData = new String(buffer,0,bytes);

    return stringData;

}

You have to construct a new string out of a byte array. The first element in your byteArray should be 0x63. If you want to add any more letters, make the byteArray longer and add them to the next indices.

byte[] byteArray = new byte[1];
byteArray[0] = 0x63;

try {
    System.out.println("string " + new String(byteArray, "US-ASCII"));
} catch (UnsupportedEncodingException e) {
    // TODO: Handle exception.
    e.printStackTrace();
}

Note that specifying the encoding will eventually throw an UnsupportedEncodingException and you must handle that accordingly.


String str = "0x63";
int temp = Integer.parseInt(str.substring(2, 4), 16);
char c = (char)temp;
System.out.print(c);

System.out.println(new String(new byte[]{ (byte)0x63 }, "US-ASCII"));

Note especially that converting bytes to Strings always involves an encoding. If you do not specify it, you'll be using the platform default encoding, which means the code can break when running in different environments.


You can use printf:

System.out.printf("string %c\n", 0x63);

You can as well create a String with such formatting, using String#format:

String s = String.format("string %c", 0x63);

Use char instead of byte:

System.out.println("string " + (char)0x63);

Or if you want to be a Unicode puritan, you use codepoints:

System.out.println("string " + new String(new int[]{ 0x63 }, 0, 1));

And if you like the old skool US-ASCII "every byte is a character" idea:

System.out.println("string " + new String(new byte[]{ (byte)0x63 },
                                          StandardCharsets.US_ASCII));

Avoid using the String(byte[]) constructor recommended in other answers; it relies on the default charset. Circumstances could arise where 0x63 actually isn't the character c.


you can use

the character equivalent to 0x63 is 'c' but byte equivalent to it is 99

System.out.println("byte "+(char)0x63); 

If it's a single byte, just cast the byte to a char and it should work out to be fine i.e. give a char entity corresponding to the codepoint value of the given byte. If not, use the String constructor as mentioned elsewhere.

char ch = (char)0x63;
System.out.println(ch);