#ifndef MARS_checksum #define MARS_checksum namespace std { class Checksum { public: uint64_t buffer; void reset() { buffer = 0; } Checksum() : buffer(0) { } Checksum(const Checksum &sum) : buffer(sum.buffer) { } Checksum(uint64_t v) : buffer(((v>>16)&0xffff) | ((v&0xffff)<<32)) { } uint32_t val() const { return (((buffer&0xffff)<<16) | ((buffer>>32)&0xffff)); } bool valid() const { return buffer==0xffff0000ffff; } void HandleCarryBits() { while (1) { const uint64_t carry = ((buffer>>48)&0xffff) | ((buffer&0xffff0000)<<16); if (!carry) break; buffer = (buffer&0xffff0000ffff) + carry; } } Checksum &operator+=(const Checksum &sum) { buffer += sum.buffer; HandleCarryBits(); return *this; } Checksum operator+(Checksum sum) const { return (sum += *this); } bool add(const char *buf, size_t len) { // Avoid overflows in carry bits if (len>262140) // 2^18-4 { add(buf, 262140); return add(buf+262140, len-262140); } if (len%4>0) { ostringstream sout; sout << "Length " << len << " not dividable by 4." << endl; #ifdef __EXCEPTIONS throw runtime_error(sout.str()); #else gLog << ___err___ << "ERROR - " << sout.str() << endl; return false; #endif } const unsigned short *sbuf = reinterpret_cast(buf); uint32_t *hilo = reinterpret_cast(&buffer); for (size_t ii = 0; ii < len/2; ii++) hilo[(ii+1)%2] += sbuf[ii]; HandleCarryBits(); return true; } bool add(const vector &v) { return add(v.data(), v.size()); } string str(bool complm=true) const { string rc(16,0); const uint8_t exclude[13] = { 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60 }; const uint32_t value = complm ? ~val() : val(); // complement each bit of the value /* for (int ii = 0; ii < 4; ii++) { uint8_t byte = (value >> (24 - (8 * ii))); const uint8_t quotient = byte / 4 + offset; const uint8_t remainder = byte % 4; uint32_t ch[4] = { quotient+remainder, quotient, quotient, quotient }; // avoid ASCII punctuation while (1) { bool check = false; for (int kk = 0; kk < 13; kk++) { for (int jj = 0; jj < 4; jj += 2) { if (ch[jj] != exclude[kk] && ch[jj+1] != exclude[kk]) continue; ch[jj]++; ch[jj+1]--; check++; } } if (!check) break; } for (int jj = 0; jj < 4; jj++) // assign the bytes rc[4*jj+ii] = ch[jj]; } return rc; */ const uint8_t *p = reinterpret_cast(&value); for (int i=0; i<4; i++) { rc[i+ 0] = '0' + p[i]/4 + p[i]%4; rc[i+ 4] = '0' + p[i]/4; rc[i+ 8] = '0' + p[i]/4; rc[i+12] = '0' + p[i]/4; } while(1) { bool ok = true; for (int i=0; i<16-4; i++) { for (int j=0; j<13; j++) if (rc[i]==exclude[j] || rc[(i+4)%16]==exclude[j]) { rc[i]++; rc[(i+4)%16]--; ok = false; } } if (ok) break; } return rc; } }; } #endif