Skip to content

Instantly share code, notes, and snippets.

@darichey
Last active November 11, 2020 04:32
Show Gist options
  • Save darichey/080b687052bc947a6d3776e4314cec83 to your computer and use it in GitHub Desktop.
Save darichey/080b687052bc947a6d3776e4314cec83 to your computer and use it in GitHub Desktop.
Internet Checksum
#include <cstdint>
#include <ios>
#include <iostream>
#include <vector>
uint16_t checksum(const std::vector<uint16_t> &data) {
uint32_t checksum = 0;
for (auto word : data) {
checksum += word;
while (checksum >> 16u != 0) {
checksum = (checksum & 0xffffu) + (checksum >> 16u);
}
}
return ~checksum;
}
uint16_t checksum(const std::vector<uint8_t> &data) {
std::vector<uint16_t> shorts;
for (int i = 0; i < data.size(); i += 2) {
uint16_t j = data[i];
j <<= 8u;
if (i + 1 < data.size()) {
j |= data[i + 1];
}
shorts.push_back(j);
}
return checksum(shorts);
}
int main() {
std::vector<uint8_t> data = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A};
std::cout << std::hex << checksum(data) << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment