How to calculate CheckSum in FIX manually?

给你一囗甜甜゛ 提交于 2020-04-07 16:06:50

问题


I have a FixMessage and I want to calculate the checksum manually.

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

The body length here is calculated:

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)

The checksum is 157 (10=157). How to calculate it in this case?


回答1:


You need to sum every byte in the message up to but not including the checksum field. Then take this number modulo 256, and print it as a number of 3 characters with leading zeroes (e.g. checksum=13 would become 013).

Link from the FIX wiki: FIX checksum

An example implementation in C, taken from 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 );   
}



回答2:


Ready-to-run C example adapted from 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\0019=49\00135=5\00134=1\00149=ARCA\00152=20150916-04:14:05.306\00156=TW\001";
    int len = sizeof(msg) / sizeof(msg[0]);
    GenerateCheckSum(msg, len);
}

Points to Note

  • GenerateCheckSum takes the entire FIX message except CheckSum field
  • Delimiter SOH is written as \001 which has ASCII value 1



回答3:


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


来源:https://stackoverflow.com/questions/32708068/how-to-calculate-checksum-in-fix-manually

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!