Search code examples
javastringtype-conversionbytedatagram

Java byte to string


So I want to convert a byte array returned by the DatagramPacket's getData() function into a string. I know the way to convert the whole byte array to string is just:

String str = new String(bytes);

However, this prints out null characters at the end. So if the byte array was

[114, 101, 113, 117, 101, 115, 116, 0, 0, 0]

The 0's print out empty boxes on the console. So I basically only want to print out:

[114, 101, 113, 117, 101, 115, 116]

So I made this function:

public void print(DatagramPacket d) {
        byte[] data = d.getData();
        for(int i=0; i< d.getLength(); i++) {
            if(data[i] != 0)
                System.out.println( data[i] );
        }
    }

But unfortunately this is printing out the actual numbers instead of the letters. So how can I convert each individual byte to a string and print that out. Or if there is another way to print the byte array without the nulls at the end then that'll be fine too.


Solution

  • Just cast each int, that is not 0, to a char. You can test it in your print:

    System.out.println((char)data[i]);