如何手动计算 FIX 中的 CheckSum?

How to calculate CheckSum in FIX manually?

我有一个FixMessage,我想手动计算校验和。

8=FIX.4.2|9=49|35=5|34=1|49=ARCA|52=20150916-04:14:05.306|56=TW|10=157|

这里的体长是这样计算的:

8=FIX.4.2|9=49|35=5|34=1|49=ARCA|52=20150916-04:14:05.306|56=TW|10=157|
0        + 0  + 5  + 5  + 8     + 26                     + 5   + 0  = 49(correct)

校验和为 157 (10=157)。在这种情况下如何计算?

您需要对消息中的每个字节求和,但不包括校验和字段。然后将这个数字取模 256,并将其打印为带前导零的 3 个字符的数字(例如 checksum=13 将变为 013)。

Link 来自 FIX wiki:FIX checksum

C 中的示例实现,摘自 onixs.biz:

char *GenerateCheckSum( char *buf, long bufLen )
{
    static char tmpBuf[ 4 ];
    long idx;
    unsigned int cks;

    for( idx = 0L, cks = 0; idx < bufLen; cks += (unsigned int)buf[ idx++ ] );
    sprintf( tmpBuf, "%03d", (unsigned int)( cks % 256 ) );
    return( tmpBuf );   
}
static void Main(string[] args)
    {
        //10=157
        string s = "8=FIX.4.2|9=49|35=5|34=1|49=ARCA|52=20150916-04:14:05.306|56=TW|";
        byte[] bs = GetBytes(s);
        int sum=0;
        foreach (byte b in bs)
            sum = sum + b;
        int checksum = sum % 256;
    }
    //string to byte[]
    static byte[] GetBytes(string str)
    {
        byte[] bytes = new byte[str.Length * sizeof(char)];
        System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
        return bytes;
    }

Ready-to-运行 C 示例改编自 here

8=FIX.4.2|9=49|35=5|34=1|49=ARCA|52=20150916-04:14:05.306|56=TW|10=157|

#include <stdio.h>

void GenerateCheckSum( char *buf, long bufLen )
{
        unsigned sum = 0;
        long i;
        for( i = 0L; i < bufLen; i++ )
        {
            unsigned val = (unsigned)buf[i];
            sum += val;
            printf("Char: %02c Val: %3u\n", buf[i], val); // print value of each byte
        }
        printf("CheckSum = %03d\n", (unsigned)( sum % 256 ) ); // print result
}

int main()
{
    char msg[] = "8=FIX.4.2[=10=]19=49[=10=]135=5[=10=]134=1[=10=]149=ARCA[=10=]152=20150916-04:14:05.306[=10=]156=TW[=10=]1";
    int len = sizeof(msg) / sizeof(msg[0]);
    GenerateCheckSum(msg, len);
}

注意事项

  • GenerateCheckSum 获取除 CheckSum 字段之外的整个 FIX 消息
  • Delimiter SOH is written as [=12=]1 which has ASCII value 1

使用 BodyLength[9] 和 CheckSum[10] 字段。 BodyLength 是从 BodyLenght 之后的字段开始计算的,并且 在 CheckSum 字段之前。 CheckSum 是从 ‘8= 到校验和字段之前的 SOH 计算的。 计算每个字符的二进制值,并将计算值的 LSB 与校验和值进行比较。 如果校验和计算为 274,则模 256 值为 18 (256 + 18 = 274)。该值将被传输为 10=018,其中 "10="是校验和字段的标记。