简体   繁体   English

字符串或双精度字节

[英]String or double to byte

I have a problem. 我有个问题。 I receive a double val=80.22. 我收到double val = 80.22。 Then I split it: 然后我将其拆分:

String[] arr=String.valueOf(val).split("\\.");
int[] intArr=new int[2];
intArr[0]=Integer.parseInt(arr[0]); // 80
intArr[1]=Integer.parseInt(arr[1]); // 22

Now i need to put this values into a byte[] . 现在,我需要将此值放入byte[] But I don't need the value into the byte[] , I need it like this: 0x80 , 0x22. 但是我不需要将值放入byte[] ,我需要像这样:0x80,0x22。

What I have tried: 我试过的

byte firstbyte = Byte.parseByte(arr[0], 16);
byte secondbyte = Byte.parseByte(arr[1], 16);

This works fine but only to the value 80, then I receive: 这可以正常工作,但只能达到值80,然后我收到:

java.lang.NumberFormatException: Value out of range. Value:"80" Radix:16

But I don't get it. 但是我不明白。 I need the number up to the value 100. 我需要不超过100的数字。

I have tried to write it into a string like string = 0x80 but I don't know how to put it into the byte[] then. 我试图将其写入字符串,例如string = 0x80,但是我不知道该如何将其放入byte[]

Thanks for your help! 谢谢你的帮助!

Its hard for me to understand the question, but if you want to put a number up to the value 100 in a byte data type you just need to write: 这让我很难理解这个问题,但是如果您想在字节数据类型中将数字最大为100,则只需编写:

    byte firstbyte = (byte)intArr[0];
    byte secondbyte = (byte)intArr[1];

Because 0x80 is an hexadecimal value and its worth to the decimal 128 which is too big for that data type. 因为0x80是十六进制值,所以它的值等于十进制128,对于该数据类型而言,该值太大。

Bytes are signed in Java. 字节在Java中签名。 The highest value in a byte , in hexadecimal is 7F, so 80 is too big. 一个byte最大值(以十六进制表示)为7F,因此80太大。 Unfortunately there is no parseUnsignedByte . 不幸的是,没有parseUnsignedByte

The workaround is to use the type with the next higher range up, a short , then cast the result back to byte . 解决方法是使用下一个较高范围的类型( short ,然后将结果转换回byte

byte firstbyte = (byte) Short.parseShort(arr[0], 16);
byte secondbyte = (byte) Short.parseShort(arr[1], 16);

This will turn "80" into -128 , but the byte representation is correct: 1000 0000 , or 80 in hexadecimal. 这会将“ 80”变成-128 ,但是字节表示是正确的: 1000 0000或十六进制的80。

Note that if the short value is out of the range of even an unsigned byte (at least 256, or "100" in hexadecimal), then this will silently truncate the value to the least significant 8 bits, ie 256 -> 0, 257 -> 1, etc. 请注意,如果short值甚至超出了无符号字节的范围(至少为256,或者十六进制为“ 100”),那么它将默默地将值截断为最低有效8位,即256-> 0,257 -> 1等

byte max value is 2^7 - 1 = 127 in dec. 字节最大值是dec中的2 ^ 7-1-= 127。

0x80 is hex representation of 128 in dec. 0x80是十进制128的十六进制表示形式。

Hex counts from 0 to 9 then from A to F. 十六进制从0到9,然后从A到F。

So, 80 in dec will be 0x50. 因此,dec中的80将为0x50。

Simply avoid second parameter in Byte.parseByte() or use Byte.valueOf("80") 只需避免在Byte.parseByte()中使用第二个参数或使用Byte.valueOf(“ 80”)

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

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