Java字节到字符串 [英] Java byte to string

查看:98
本文介绍了Java字节到字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想将DatagramPacket的getData()函数返回的字节数组转换为字符串。我知道将整个字节数组转换为字符串的方法只是:

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]

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]

所以我做了这个功能:

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.

推荐答案

只需将每个不为0的int强制转换为char。您可以在打印中对其进行测试:

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

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

这篇关于Java字节到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆