top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Is there any way to find out check sum of a string?

+2 votes
339 views

I want to pass a string over the network, After Coding and Decoding How will i make sure that this is the same string ?

posted May 14, 2015 by Chirag Gangdev

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote
 
Best answer

There is no need if data is transferred over TCP/IP as it is taken care by the IP layer. You can have your own implementation of the cksum or you can use the following C code for the cksum calculation (picked from net for IP cksum)

uint16_t ip_checksum(void* vdata,size_t length) {
    // Cast the data pointer to one that can be indexed.
    char* data=(char*)vdata;

    // Initialise the accumulator.
    uint64_t acc=0xffff;

    // Handle any partial block at the start of the data.
    unsigned int offset=((uintptr_t)data)&3;
    if (offset) {
        size_t count=4-offset;
        if (count>length) count=length;
        uint32_t word=0;
        memcpy(offset+(char*)&word,data,count);
        acc+=ntohl(word);
        data+=count;
        length-=count;
    }

    // Handle any complete 32-bit blocks.
    char* data_end=data+(length&~3);
    while (data!=data_end) {
        uint32_t word;
        memcpy(&word,data,4);
        acc+=ntohl(word);
        data+=4;
    }
    length&=3;

    // Handle any partial block at the end of the data.
    if (length) {
        uint32_t word=0;
        memcpy(&word,data,length);
        acc+=ntohl(word);
    }

    // Handle deferred carries.
    acc=(acc&0xffffffff)+(acc>>32);
    while (acc>>16) {
        acc=(acc&0xffff)+(acc>>16);
    }

    // If the data began at an odd byte address
    // then reverse the byte order to compensate.
    if (offset&1) {
        acc=((acc&0xff00)>>8)|((acc&0x00ff)<<8);
    }

    // Return the checksum in network byte order.
    return htons(~acc);
}
answer May 14, 2015 by Salil Agrawal
Similar Questions
+1 vote

Is there any method in c++ to find the multiple position of a char in a string.
eg : Hi, How are you?
position of H : 1 and 5

0 votes

Is there any command in docker by which I can list down list of images/layers that have been used to construct a particular image ?

...