CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Mar 2004
    Posts
    382

    Calculating Sum of bytes (checksum) for char []

    Does anyone now a simple code on how I can calculate the sum of all bytes in a char [] array? Any advice would be appreciated.

    Thanks.

  2. #2
    Join Date
    Sep 2001
    Location
    San Diego
    Posts
    2,147
    A simple way is to add them all up...

    Code:
    char MyArray[] = "some text";
    char checksum = 0; // could be an int if preferred
    int SizeOfArray = strlen(MyArray);
    
    for(int x = 0; x < SizeOfArray; x++)
    {
          checksum += MyArray[x];
    }
    
    printf("Checksum for MyArray is: %d\n", checksum);
    There are more complex (and accurate) ways, but it depends on your needs. CRC checking is a good way of checking if you want to really determine whether the string matches some other string with a high degree of certainty. There are many articles on line about CRC checking (and probably several API's available to help you).

    Hope this helps,

    - Nigel

  3. #3
    Join Date
    Apr 2000
    Location
    Mesa, AZ
    Posts
    189
    I happen to have created a dialog that does just that (for any file that is in binary format.) The zip file is attached. You have to add the FastFileIO.lib to the object/library modules line in your project settings because I wrote my own IO library for reading in large files that I use for that purpose (you can substitute CFile reads in if you like.) Also you need to copy the dll to either the directory you are running from or your sys32 directory so it gets included in your path. You're free to look through the code and examine it and use it for personal use. (Please don't copy my code for commercial use.) I think everything is there, email me (zebenir@hotmail.com) if you end up having problems.
    Attached Files Attached Files

  4. #4
    Join Date
    Jan 2004
    Location
    Earth
    Posts
    567
    The original post indicated the sum of the bytes and also indicated checksum. I always understood the checksum to be the 2's complement of the sum of the bytes. Therefore the checksum is actually different than just the sum of the bytes. If you just want the sum of the bytes NigelQ's code is correct. If you want the checksum, NigelQ's code would need to be modified to take the bitwise complement of the sum and then add 1. So the following would need to be added after the for loop and before the printf statement if you want the checksum.

    Code:
     //Perform bitwise inversion 
    checksum=~checksum;
    //Increment
    checksum++;
    TDM
    Last edited by TDM; April 28th, 2004 at 10:02 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured