java 16进制字节数组,在Java中将十六进制数据读入字节数组中?

I'm reading data from an SNES ROM using Java. I am opening a stream and reading in the bytes into an array:

InputStream stream = open("foo.rom");

final int startingSize = stream.available();

byte[] data = new byte[startingSize];

final int numberRead = stream.read(data, 0, startingSize);

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 E4 corresponds to -28 in two's complement.

You can convert signed bytes to pretend-unsigned-ints by doing something like String.valueOf(data[ref] & 0x00FF). That will strip off the sign bit and auto-convert to an int.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值