如何计算校验和的“二进制值加字符”

时间:2012-02-20 16:52:01

标签: java

在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

非常感谢你的帮助。

1 个答案:

答案 0 :(得分:1)

您的规范说:

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

这是一个返回预期结果的片段,但我不知道帧编号来自哪里(确保在您的规范中的其他地方)

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));
}

}