java 在java中将十六进制字符串转换为整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/362278/
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-29 12:05:38  来源:igfitidea点击:

convert hexadecimal character string to integer in java

javacore

提问by Jon Skeet

I'm begginer in java I'm reading data from serial port and I have stored the data in string array data is 24 byte length.

我是 Java 初学者,我正在从串行端口读取数据,并将数据存储在字符串数组中,数据长度为 24 字节。

Data I'm getting as output: 12120814330006050.0

我作为输出得到的数据:12120814330006050.0

data also contains hexadecimal character in the string I want to read first character of the string. I have done:

data 还包含字符串中的十六进制字符我想读取字符串的第一个字符。我已经做好了:

String str=dispArray[i].substring(1,2);
int i= Integer.parseInt(str,16);
System.out.println("Decimal:="+ i);

But I'm getting NumberFormatException.plz help me to read hexadecimal character.

但是我得到 NumberFormatException.plz 帮助我读取十六进制字符。

Thanks for reply

谢谢你的回复

回答by Markus Lausberg

single characters you can get from a string with

您可以从字符串中获取的单个字符

str.getChar(0);

When you know that the string contains hex values in every character you dont have to convert every single character. You can put the complete string in and get the dec value of the hex string back. Otherwise you only calculate 1 hex value and has to multiplicate with the index number of the character position.

当您知道字符串在每个字符中都包含十六进制值时,您就不必转换每个字符。您可以将完整的字符串放入并获取十六进制字符串的 dec 值。否则,您只计算 1 个十六进制值,并且必须乘以字符位置的索引号。

To parse it to an hex value you can call

要将其解析为十六进制值,您可以调用

Integer.parseInt(str,16);

回答by Jon Skeet

It sounds like your data stream actually contains a mixture of binary and text data. It's very important (IMO) that you don'ttry to store the whole thing as a string. Keep it as binary data, and convert appropriate chunks into text when you need to.

听起来您的数据流实际上包含二进制和文本数据的混合。非常重要(IMO)您不要尝试将整个内容存储为字符串。将其保留为二进制数据,并在需要时将适当的块转换为文本。

This may mean changing how you're reading from the serial port in the first place - use APIs which deal in bytes and byte arrays instead of chars and strings.

这可能意味着首先要改变从串行端口读取的方式 - 使用处理字节和字节数组而不是字符和字符串的 API。

回答by Douglas Leeder

Java strings are unicode - so the bytes have already been decoded using some encoding (probably UTF-8?).

Java 字符串是 unicode - 所以字节已经使用某种编码(可能是 UTF-8?)进行解码。

So:

所以:

  1. Check the contents of the string.
  2. Check the contents of the substring.
  1. 检查字符串的内容。
  2. 检查子字符串的内容。