Java byte to string

て烟熏妆下的殇ゞ 提交于 2019-12-10 11:33:31

问题


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.


回答1:


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

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



回答2:


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]);     
}


来源:https://stackoverflow.com/questions/20112935/java-byte-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!