[英]String to byte in java
I have a problem in converting String
(contains hexadecimal value) to byte
. 我在将
String
(包含十六进制值)转换为byte
遇到问题。 Like below code. 像下面的代码。
String hexaString = "0xA1";
byte hexaByte = (byte)hexaString;
Not able to convert from String to byte like this code (Getting the Error : Cannot cast from String to byte
). 无法像这样的代码从String转换为字节(获取错误:
Cannot cast from String to byte
)。
But i am able to do like this 但是我可以这样
byte hexaByte = (byte)0xA1; //this is giving output as -95
Anyone please guide me how can i do like the first method(this also output the value -95). 任何人都请指导我如何做第一种方法(这也会输出值-95)。 Because, the last two digit i will get from db and i need to convert it to hexadecimal(appending 0x).
因为,我将从db获得最后两位数字,我需要将其转换为十六进制(附加0x)。 Then i should send to client as a byte value.
然后,我应该将字节值发送给客户端。
Thanks in Advance ! 提前致谢 !
You can do something like: 您可以执行以下操作:
byte hexaByte = Byte.parseByte("1A", 16);
where 16 is radix (base of system numeration), but if the number is higer than 127 it will cause NumberFormatException. 其中16是基数(系统计算的基数),但是如果数字大于127,则将导致NumberFormatException。
如果需要使用0x前缀,则(byte) Integer.decode("0xA1")
会做正确的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.