简体   繁体   English

将字节字符串转换为ASCII

[英]Convert a String of bytes into ASCII

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: dIn是:

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. 先感谢您。

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: 第一次使用:

String text = new String(data, 0, data.length, "ASCII");

For the second you could use something like Apache Commons Codec : 对于第二个,您可以使用类似Apache Commons Codec的东西:

String text = Hex.encodeHexString(data);

Have a look at String's Format function . 看一下String的Format函数 If you specify the format as "%X", it will be returned as a hex string 如果您将格式指定为“%X”,它将以十六进制字符串形式返回

You will have to iterate through the byte array to convert each, as the above function accepts only primitive numeric types. 您将不得不遍历字节数组来转换每个字节数组,因为上述函数仅接受原始数字类型。

Wrap the DataInputStream in an InputStreamReader . DataInputStream包装在InputStreamReader中

DataInputStream.readLine() is deprecated. 不推荐使用DataInputStream.readLine()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM