fork(2) download
  1. #include <iostream>
  2. #include <inttypes.h>
  3.  
  4. uint64_t fletcher64_A(const uint8_t * data, uint64_t count)
  5. {
  6. // calculate how many full double words the input has
  7. uint64_t dwords = count / 4;
  8. // now calculate the flechter-64 checksum from double words
  9. uint64_t sum1 = 0;
  10. uint64_t sum2 = 0;
  11. const uint32_t * data32 = reinterpret_cast<const uint32_t*>(data);
  12. for (uint64_t index = 0; index < dwords; ++index)
  13. {
  14. sum1 = (sum1 + data32[index]) % UINT32_MAX;
  15. sum2 = (sum2 + sum1) % UINT32_MAX;
  16. }
  17. // calculate how many extra bytes, that do not fit into a double word, the input has
  18. uint64_t remainingBytes = count - dwords * 4;
  19. if (remainingBytes > 0)
  20. {
  21. // copy the excess bytes to our dummy variable. you could use memcpy here...
  22. uint32_t dummy = 0;
  23. for (uint64_t index = 0; index < remainingBytes; ++index)
  24. {
  25. reinterpret_cast<uint8_t*>(&dummy)[index] = data[dwords * 4 + index];
  26. }
  27. // now add the dummy on top
  28. sum1 = (sum1 + dummy) % UINT32_MAX;
  29. sum2 = (sum2 + sum1) % UINT32_MAX;
  30. }
  31. // build final checksum
  32. return (sum2 << 32) | sum1;
  33. }
  34.  
  35. uint64_t fletcher64_B(const uint8_t * data, uint64_t count)
  36. {
  37. // calculate how many full double words the input has
  38. uint64_t dwords = count / 4;
  39. // now calculate the flechter-64 checksum from double words
  40. uint32_t sum1 = 0;
  41. uint32_t sum2 = 0;
  42. const uint32_t * data32 = reinterpret_cast<const uint32_t*>(data);
  43. for (uint64_t index = 0; index < dwords; ++index)
  44. {
  45. sum1 += data32[index];
  46. sum2 += sum1;
  47. }
  48. // calculate how many extra bytes, that do not fit into a double word, the input has
  49. uint64_t remainingBytes = count - dwords * 4;
  50. if (remainingBytes > 0)
  51. {
  52. // copy the excess bytes to our dummy variable. you could use memcpy here...
  53. uint32_t dummy = 0;
  54. for (uint64_t index = 0; index < remainingBytes; ++index)
  55. {
  56. reinterpret_cast<uint8_t*>(&dummy)[index] = data[dwords * 4 + index];
  57. }
  58. // now add the dummy on top
  59. sum1 += dummy;
  60. sum2 += sum1;
  61. }
  62. // build final checksum
  63. return ((uint64_t)sum2 << 32) | sum1;
  64. }
  65.  
  66. int main() {
  67. const std::string data = "abcdefghijklmnopqrstuvwxyz0123456789helloworld!";
  68. uint64_t ca = fletcher64_A(reinterpret_cast<const uint8_t*>(data.data()), data.size());
  69. uint64_t cb = fletcher64_B(reinterpret_cast<const uint8_t*>(data.data()), data.size());
  70. std::cout << "String size: " << data.size() << ", checksum a: 0x" << std::hex << ca << ", checksum b: 0x" << cb << std::endl;
  71. return 0;
  72. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
String size: 47, checksum a: 0x90651cd4152ab0aa, checksum b: 0x90651cb7152ab0a6