2

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.

Richard
  • 5,840
  • 36
  • 123
  • 208
  • "So I want to convert a byte array returned by the DatagramPacket's getData() function into a string." - What encoding was used to convert the original text data into binary data? – Jon Skeet Nov 21 '13 at 05:12
  • possible duplicate of [What is character encoding and why should I bother with it](http://stackoverflow.com/questions/10611455/what-is-character-encoding-and-why-should-i-bother-with-it) – Raedwald Apr 10 '15 at 12:03

2 Answers2

2

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

System.out.println((char)data[i]);
spydon
  • 9,372
  • 6
  • 33
  • 63
  • You don't take the character encoding into account. It will work if the data is for example ASCII (because that's compatible with how characters are stored in Java), if not then you'll get strange results. – Jesper Nov 21 '13 at 06:28
  • @Jesper: I don't think there is a way of taking it into consideration if he doesn't specify which character encoding the data comes back in? – spydon Nov 21 '13 at 06:40
  • Because Richard didn't say anything about what character encoding the data is in, we can't take it into account, I just commented because he needs to be aware of it. – Jesper Nov 21 '13 at 10:06
0

If you want to convert byte array into String then you can just use String(byte[] bytes) or String(byte[] bytes, Charset charset) constructors like,

byte[] b=new byte[10];
b[0]=100;    
b[1]=101;
b[2]=102;
b[3]=0;
b[4]=0;     
String st=new String(b);    
System.out.println(st);//def

but if you want to print single character then

char[] c=st.toCharArray();     
for(int i=0;i<c.length;i++){   
    System.out.println(c[i]);     
}
Nayuki
  • 17,911
  • 6
  • 53
  • 80