在Java中将十六进制数据读入字节数组中? [英] Reading hexadecimal data into byte array in Java?
问题描述
我正在使用Java从SNES ROM读取数据。我打开一个流并将字节读入一个数组中:
InputStream stream = open(foo.rom);
final int startingSize = stream.available();
byte [] data = new byte [startingSize];
final int numberRead = stream.read(data,0,startingSize);
在ROM中,我有这个值:
E4 2B 00 02 03 00 FF 3A 00 83
228 43 0 2 3 0 255 58 0 131(十进制)
然而,我的代码行为怪异。在设置了一些调试语句之后,当使用String.valueOf(data [ref])打印时,我有这个模式:
-28 43 0 2 3 0 - 1 58 0 -125 (ROM中的这个地址是数据出现的第一个地址,但我注意到程序中其他地方的值不正确。) 尽我所能地告诉我的Java字节数组并不尊重十六进制数据。我怎样才能设置我的字节数组呢? Java将所有字节视为签名,因此它们只能处于范围-128至+127。位模式 您可以将带符号字节转换为pretend-unsigned-通过执行类似于 I'm reading data from an SNES ROM using Java. I am opening a stream and reading in the bytes into an array: In the ROM, I have this value: E4 2B 00 02 03 00 FF 3A 00 83 228 43 0 2 3 0 255 58 0 131 (in decimal) However, my code is behaving weirdly. After setting up some debug statements, I have this pattern when printing with String.valueOf(data[ref]): -28 43 0 2 3 0 -1 58 0 -125 (This address in the ROM is the first where data appears, but I am noticing incorrect values elsewhere in the program.) As near as I can tell my Java byte array is not respecting the hexadecimal data. How can I set my byte array to do so? Java treats all bytes as being signed, so they can only be in the range -128 to +127. The bit pattern You can convert signed bytes to pretend-unsigned-ints by doing something like 这篇关于在Java中将十六进制数据读入字节数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
E4
对应于二进制补码中的-28。
String.valueOf(data [ref]& 0x00FF)
的整数。这将剥离符号位并自动转换为int。InputStream stream = open("foo.rom");
final int startingSize = stream.available();
byte[] data = new byte[startingSize];
final int numberRead = stream.read(data, 0, startingSize);
E4
corresponds to -28 in two's complement.String.valueOf(data[ref] & 0x00FF)
. That will strip off the sign bit and auto-convert to an int.