将字节字符串转换为 ASCII
我正在连接到一个蓝牙设备,它回答我发送的一些参数,但作为响应,我从这样的套接字读取:
String data = dIn.readLine();
其中 dIn 是:
DataInputStream dIn = new DataInputStream(socket.getInputStream());
问题是我收到了数据,但它是一个字节数组读取一个字符串。如何将包含字节数组的字符串转换为具有正确的十六进制值的字符串?
先感谢您。
I'm connecting to a bluetooth device that answers to some parameters I send it, but as a response I read from a socket like this:
String data = dIn.readLine();
Where dIn is a:
DataInputStream dIn = new DataInputStream(socket.getInputStream());
The thing is that I receive the data, but it's a byte array read on a string. How can I convert that string that contains my byte array into a String with the correct hexadecimal values?
Thank you in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
目前尚不清楚您是否正在尝试对字节数组形式的文本字符串进行解码,或者您是否想要任意二进制数据的文本表示形式(以十六进制表示)。对于第一个,您可以使用:
对于第二个,您可以使用类似 Apache Commons Codec 的东西:
It's unclear whether you're trying to actually decode a text string which you've got as a byte array, or whether you want a text representation (in hex) of arbitrary binary data. For the first you'd use:
For the second you could use something like Apache Commons Codec:
看看 String 的 格式化函数。如果指定格式为“%X”,则会返回作为十六进制字符串
您必须迭代字节数组才能转换每个字节,因为上面的函数仅接受原始数字类型。
Have a look at String's Format function. If you specify the format as "%X", it will be returned as a hex string
You will have to iterate through the byte array to convert each, as the above function accepts only primitive numeric types.
将
DataInputStream
包装在 输入流读取器。DataInputStream.readLine()
已弃用。Wrap the
DataInputStream
in an InputStreamReader.DataInputStream.readLine()
is deprecated.