gpt4 book ai didi

java - 如何将字符串(字节数组作为字符串)转换为短字符串

转载 作者:行者123 更新时间:2023-12-01 16:44:30 24 4
gpt4 key购买 nike

你好,我想将字节数组(即 0x3eb)转换为短数组,所以我将 0x3eb 视为字符串并尝试转换为短数组,但它抛出 Numberformat 异常...请有人帮助我

import java.io.UnsupportedEncodingException;
public class mmmain
{

public static void main(String[] args) throws UnsupportedEncodingException
{
String ss="0x03eb";
Short value = Short.parseShort(ss);
System.out.println("value--->"+value);
}
}


Exception what im getting is
Exception in thread "main" java.lang.NumberFormatException:
For input string: "0x3eb" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:491)
at java.lang.Short.parseShort(Short.java:117)
at java.lang.Short.parseShort(Short.java:143)
at mmmain.main(mmmain.java:14)

即使我尝试将 0x3eb 转换为字节

byte[] 字节 = ss.getBytes();

但我没有找到任何将字节解析为短的实现。

提前致谢

最佳答案

请参阅doc parseShort:

Parses the string argument as a signed decimal short. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value.

待解析的字符串只能包含小数字符和符号字符,不能包含0x前缀。

尝试:

String ss="3eb";
Short value = Short.parseShort(ss, 16);

关于java - 如何将字符串(字节数组作为字符串)转换为短字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54958209/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com