如何一起添加多个字节?

时间:2010-10-22 23:19:01

标签: java byte bytearray

我正在尝试编写一个ROM文件修补程序,我在文档中提到了这个:

The next three bytes are the place in the destination file
(the file to be patched) where a change is to be made.

The two bytes following that are the length of the amount
of data to be changed.

如何将这三个和两个字节正确地转换为java中的单个数字?

2 个答案:

答案 0 :(得分:2)

奇怪的是,我看到 Joey 的有效回答,他在10分钟前删除了该回复:

(byte1 << 16) + (byte2 << 8) + byte3

我唯一需要添加的内容:不要将从InputStream读取的字节转换为byte类型(InputStream#read返回0到255之间的int值。例如,这会在255中转为-1,我们不需要这样的副作用。

所以,它可能看起来像

(in.read() << 16) + (in.read() << 8) + in.read()

答案 1 :(得分:1)

确保使用InputStream的后代(byte vs char input)。

最重要的问题是数据是以“小端”还是“大端”方式存储的。我会假设小端(x86)。对于三字节数字:

FileInputStream fs = new FileInputStream(...);

int byte1 = fs.read();
int byte2 = fs.read();
int byte3 = fs.read();
int data = (byte3 << 16) | (byte2 << 8) | byte1;

对于little-endian,读取的第一个字节是最低有效字节。

如果您需要big-endian,请将最后一行更改为:

int data = (byte1 << 16) | (byte2 << 8) | byte3;