我尝试用 Java 计算 Sega Genesis rom 文件的校验和。为此,我想将从 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;
}
我了解代码的作用。它将所有 16 位数字相加(由两个 8 位数字组合而成)。但我不明白的是 uint16 的溢出发生了什么以及它如何转移到 Java 代码?
编辑:此代码似乎有效,谢谢:
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();
}