十六进制值的十进制表示错误

时间:2022-10-15 17:08:23

I have a small data set in HexaDecimal Representation -

我在HexaDecimal Representation中有一个小数据集 -

byte[] bb = new byte[] { (byte)0x7D, (byte)0x44, (byte)0xCC };

byte [] bb = new byte [] {(byte)0x7D,(byte)0x44,(byte)0xCC};

To understand how the values are coming in Decimal Representation, I did the following -

为了理解值在十进制表示中的来源,我做了以下 -

Log.i("DECIMAL VALUE of 7D>>", buf[i] + "");
Log.i("DECIMAL VALUE of 44>>", buf[i+1] + "");
Log.i("DECIMAL VALUE of CC>>", buf[i+2] + "");

And what it printed was -

它印刷的是 -

DECIMAL VALUE of 7D>> 125

DECIMAL VALUE of 44>> 68

DECIMAL VALUE of CC>> -52

Looking into the site -

展望网站 -

http://hextodecimal.com/index.php?hex=CC

http://hextodecimal.com/index.php?hex=CC

The Decimal Representation of byte CC is 204.

字节CC的十进制表示是204。

In my application I am getting Index Out Of Bounds Exception just because index at -52 doesn't exist in the bounds.

在我的应用程序中,我得到Index Out Of Bounds Exception,因为在-52中的索引不存在于边界中。

So how is this byte coming negative and what is the clear solution.

那么这个字节如何变为负面,什么是明确的解决方案。

1 个解决方案

#1


1  

Bytes in Java are signed i.e. they range from -128 to 127. If you want to represent the number 204, use an int.

Java中的字节是有符号的,即它们的范围是-128到127.如果要表示数字204,请使用int。

int[] bb = new int[] { 0x7D, 0x44, 0xCC };

If you really want to store the data as bytes, you can convert it to unsigned where you use it to index in an array.

如果您确实希望将数据存储为字节,则可以将其转换为unsigned,在此处使用它来在数组中进行索引。

yourArray[bb[1] && 0xFF]

See the following question: How to Convert Int to Unsigned Byte and Back

请参阅以下问题:如何将Int转换为无符号字节和后退

#1


1  

Bytes in Java are signed i.e. they range from -128 to 127. If you want to represent the number 204, use an int.

Java中的字节是有符号的,即它们的范围是-128到127.如果要表示数字204,请使用int。

int[] bb = new int[] { 0x7D, 0x44, 0xCC };

If you really want to store the data as bytes, you can convert it to unsigned where you use it to index in an array.

如果您确实希望将数据存储为字节,则可以将其转换为unsigned,在此处使用它来在数组中进行索引。

yourArray[bb[1] && 0xFF]

See the following question: How to Convert Int to Unsigned Byte and Back

请参阅以下问题:如何将Int转换为无符号字节和后退