使用预期结果计算 Java 中 byte[] 的校验和
Computing Checksum of byte[] in Java with expected result
我需要一些帮助来解决我无法解决的问题。我要做的是计算一个已知字节 [] 的校验和。让我们从已知值开始:
我必须将一个 8 位数的值转换为 8 个字节的 ASCII:
Value = 33053083
Converted (asciiValue) = 33:33:30:35:33:30:38:33
这是正确的,因为它符合给我的预期值。
接下来,我需要"Compute the checksum of the ASCII value (asciiValue). Extract the last 2 digits (right justified). The result is the 'Checksum'."
我知道这个计算出的校验和的值应该是 99。
我到处都找遍了,几乎什么都试过了,但我想不出 99 的期望值。
感谢您的帮助!
编辑以添加给定算法(在 C 中):
unsigned char
vls_byteSum(char *blk, int len)
{
int i;
unsigned char sum = 0;
for (i=0; i < len; ++i)
sum += blk[i];
return sum;
}
下面的代码应该可以为您完成。
public static int checkSum(byte[] input) {
int checkSum = 0;
for(byte b : input) {
checkSum += b & 0xFF;
}
return checkSum;
}
b & 0xFF
将字节转换为整数并赋予其无符号值,这意味着 255 将被解释为 255 而不是 -1。
您在评论中发布的代码几乎正确,只是将 char
更改为 byte
:
public static byte vls_byteSum(byte[] blk) {
byte sum = 0;
for (int i = 0; i < blk.length; i++)
sum += blk[i];
return sum;
}
用这个测试它:
byte result = vls_byteSum(new byte[] { 0x33, 0x33, 0x30, 0x35, 0x33, 0x30, 0x38, 0x33 });
System.out.printf("0x%02x = %d = %d", result, result, Byte.toUnsignedInt(result));
输出:
0x99 = -103 = 153
我需要一些帮助来解决我无法解决的问题。我要做的是计算一个已知字节 [] 的校验和。让我们从已知值开始:
我必须将一个 8 位数的值转换为 8 个字节的 ASCII:
Value = 33053083
Converted (asciiValue) = 33:33:30:35:33:30:38:33
这是正确的,因为它符合给我的预期值。
接下来,我需要"Compute the checksum of the ASCII value (asciiValue). Extract the last 2 digits (right justified). The result is the 'Checksum'."
我知道这个计算出的校验和的值应该是 99。
我到处都找遍了,几乎什么都试过了,但我想不出 99 的期望值。
感谢您的帮助!
编辑以添加给定算法(在 C 中):
unsigned char
vls_byteSum(char *blk, int len)
{
int i;
unsigned char sum = 0;
for (i=0; i < len; ++i)
sum += blk[i];
return sum;
}
下面的代码应该可以为您完成。
public static int checkSum(byte[] input) {
int checkSum = 0;
for(byte b : input) {
checkSum += b & 0xFF;
}
return checkSum;
}
b & 0xFF
将字节转换为整数并赋予其无符号值,这意味着 255 将被解释为 255 而不是 -1。
您在评论中发布的代码几乎正确,只是将 char
更改为 byte
:
public static byte vls_byteSum(byte[] blk) {
byte sum = 0;
for (int i = 0; i < blk.length; i++)
sum += blk[i];
return sum;
}
用这个测试它:
byte result = vls_byteSum(new byte[] { 0x33, 0x33, 0x30, 0x35, 0x33, 0x30, 0x38, 0x33 });
System.out.printf("0x%02x = %d = %d", result, result, Byte.toUnsignedInt(result));
输出:
0x99 = -103 = 153