【发布时间】:2021-04-01 13:59:16
【问题描述】:
我有一个任务来计算一些 8 位二进制数的校验和。 我已经走了很长一段路,但由于某种原因,它给了我错误的结果。例如,如果 x 是:10101010 并且 y 是:01101111,则校验和将为 11100110。但我的代码给出了校验和 01101110(反转全部)。 请注意求和的取反发生在一个不同的、已经建立的方法中。这意味着我的方法返回 10010001,但应该返回 00011001。
我哪里出错了?
Octet 方法已经生成。
int[] x = new int[8];
Octet(String s){
if (s.length() != 8) {
System.out.println("Too few or too many characters");
return;
}
for (int i = 0; i < 8; i++) {
if (s.charAt(i) == '1') {
x[7 - i] = 1;
}
else {
x[7 - i] = 0;
}
}
}
Octet sum(Octet y) {
Octet result = new Octet("00000000");
int carry = 0;
for(int i = 0; i < 8; i++) {
result.x[i] = x[i] ^ y.x[i] + carry;
carry = x[i] & y.x[i];
}
if(carry == 1) {
for(int i = 0; i < 8 && carry == 0; i++) {
result.x[i] = result.x[i] ^ carry;
carry = result.x[i] & carry;
}
}
return result;
}
【问题讨论】:
-
第二个
for循环永远不会循环,因为如果carry == 1,循环的条件是false。什么是Octet?为什么你将y传递给你的函数,却将x作为外部变量访问? -
@CryptoFool 使用八位字节方法更新。它基本上是 8 位长,只包含 1 和 0。
-
这些八位字节的现有代码:
x = Octet{[0, 1, 0, 1, 0, 1, 0, 1]}; y = Octet{[1, 1, 1, 1, 0, 1, 1, 0]};返回Octet{[1, 0, 2, 0, 1, 0, 2, 1]},因此您应该更新代码并澄清校验和计算。 ` -
我猜这一切都属于
class Octet { }块。
标签: java calculator checksum 8-bit