Last active
November 11, 2020 04:32
-
-
Save darichey/080b687052bc947a6d3776e4314cec83 to your computer and use it in GitHub Desktop.
Internet Checksum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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