gpt4 book ai didi

java - 如何计算 "binary values addition of characters"的校验和

转载 作者:太空宇宙 更新时间:2023-11-04 08:21:59 24 4
gpt4 key购买 nike

在 Java 中工作,这是我为了实现字符消息校验和计算而制定的规范:

    8.3.3 Checksum—The checksum permits the receiver to detect a defective frame. The checksum is encoded as two characters which are sent after the <ETB> or <ETX> character. The checksum is computed by adding the  binary values of the characters, keeping the least significant eight bits of the result.
8.3.3.1 The checksum is initialized to zero with the <STX> character. The first character used in computing the checksum is the frame number. Each character in the message text is added to the checksum (modulo 256). The computation for the checksum does not include <STX>, the checksum characters, or the trailing <CR> and <LF>.
8.3.3.2 The checksum is an integer represented by eight bits, it can be considered as two groups of four bits. The groups of four bits are converted to the ASCII characters of the hexadecimal representation. The two ASCII characters are transmitted as the checksum, with the most significant character first.
8.3.3.3 For example, a checksum of 122 can be represented as 01111010 in binary or 7A in hexadecimal. The checksum is transmitted as the ASCII character 7 followed by the character A.

这是我所理解和实现的,但它似乎不起作用......:

    private void computeAndAddChecksum(byte[] bytes, OutputStream outputStream) {
logBytesAsBinary(bytes);
long checksum = 0;
for (int i = 0; i < bytes.length; i++) {
checksum += (bytes[i] & 0xffffffffL);
}
int integerChecksum = (int)checksum;
String hexChecksum = Integer.toHexString(integerChecksum).toUpperCase();
logger.info("Checksum for "+new String(bytes)+" is "+checksum+" in hexa: "+hexChecksum);
try {
if (outputStream != null)
{
outputStream.write(hexChecksum.getBytes());
}
} catch (IOException e) {
logger.error(e.getMessage());
}
}

您知道为什么此代码片段不符合规范吗?这是我得到的一个例子,如果它可以帮助的话:

    <STX>3L|1<CR><ETX>3C<CR><LF>

所以校验和

    3L|1<CR><ETX>

应该是

    3C

非常感谢您的帮助。

最佳答案

您的规范说明:

  • 校验和应使用帧号进行初始化。

这是一个返回预期结果的代码片段,但我不知道帧号来自哪里(当然在规范的其他地方)

public class ChecksumBuilder {
public static String getFrameCheckSum(String frametext,int framenum)
{
byte[] a=frametext.getBytes();

int checksum=framenum;
for(int i=0;i<a.length;i++)
{
checksum+=a[i];
}

String out=String.format("%02x",(checksum & 0xFF)).toUpperCase();
return out;
}

public static void main(String[] args)
{
System.out.print(ChecksumBuilder.getFrameCheckSum("3L|1<CR>",1));
}

}

关于java - 如何计算 "binary values addition of characters"的校验和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9364999/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com