简体   繁体   English

Java中的位操作C源代码

[英]Bit manipulation C source in Java

I try to calculate the checksum of a Sega Genesis rom file in Java. 我尝试用Java计算Sega Genesis rom文件的校验和。 For this i want to port a code snipped from C into Java: 为此,我想将从C剪切的代码移植到Java中:

static uint16 getchecksum(uint8 *rom, int length)
{
  int i;
  uint16 checksum = 0;

  for (i = 0; i < length; i += 2)
  {
    checksum += ((rom[i] << 8) + rom[i + 1]);
  }

  return checksum;
}

I understand what the code does. 我理解代码的作用。 It sums all 16bit numbers (combined from two 8 bit ones). 它将所有16位数字相加(由两个8位数字组合而成)。 But what i didn't understand is what's happening with the overflow of the uint16 and how this transfers to Java code? 但是我不明白的是,uint16的溢出以及它如何转移到Java代码会发生什么?

Edit: This code seems to work, thanks: 编辑:此代码似乎工作,谢谢:

int calculatedChecksum = 0;
int bufferi1=0;
int bufferi2=0;
bs = new BufferedInputStream(new FileInputStream(this.file));

bufferi1 = bs.read();
bufferi2 = bs.read();
while(bufferi1 != -1 && bufferi2 != -1){
    calculatedChecksum += (bufferi1*256 + bufferi2);
    calculatedChecksum = calculatedChecksum % 0x10000;
    bufferi1 = bs.read();
    bufferi2 = bs.read();
}

Simply put, the overflow is lost. 简单地说,溢出就丢失了。 A more correct approach (imho) is to use uint32 for summation, and then you have the sum in the lower 16 bits, and the overflow in the upper 16 bits. 一个更正确的方法(imho)是使用uint32求和,然后你得到低16位的和,高16位的溢出。

static int checksum(final InputStream in) throws IOException {
  short v = 0;
  int c;
  while ((c = in.read()) >= 0) {
    v += (c << 8) | in.read();
  }
  return v & 0xffff;
}

This should work equivalently; 这应该等效地工作; by using & 0xffff , we get to treat the value in v as if it were unsigned the entire time, since arithmetic overflow is identical wrt bits. 通过使用& 0xffff ,我们可以将v的值视为整个时间内的无符号,因为算术溢出与wrt位相同。

You want addition modulo 2 16 , which you can simply spell out manually: 你想要额外的模2 16 ,你可以简单地手动拼出:

checksum = (checksum + ((rom[i] << 8) + rom[i + 1])) % 0x10000;
//                                                   ^^^^^^^^^

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

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