java 将字节字符串转换为 ASCII

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7793504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 21:28:52  来源:igfitidea点击:

Convert a String of bytes into ASCII

javaandroidsocketsbyte

提问by Sonhja

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.

先感谢您。

回答by Jon Skeet

It's unclear whether you're trying to actuallydecode 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);

回答by Nicolas

Have a look at String's Format function. If you specify the formatas "%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.

您必须遍历字节数组以转换每个数组,因为上述函数仅接受原始数字类型。

回答by Graham Borland

Wrap the DataInputStreamin an InputStreamReader.

将 包装DataInputStreamInputStreamReader 中

DataInputStream.readLine()is deprecated.

DataInputStream.readLine()已弃用。