RFC1071 Internet Checksum -- gawk
@include "internet_checksum.gawk";
{
printf("Internet Checksum\nInput:\t%s\nValue:\t%d\n", $0 ,internet_checksum($0));
}
#! /usr/bin/gawk
# RFC1071 Computing the Internet Checksum (in gawk)
# written by Sean Summers <seansummers@gmail.com> 2015-09-15 v0.1
#
# use '@include "internet_checksum.gawk"' to include in a script
function _ord_init(low, high, i, t) {
# creates _ord_ array for ascii lookup
low = 0; high = 127;
for (i = low; i <= high; i++) {
t = sprintf("%c", i);
_ord_[t] = i;
}
}
function internet_checksum(str, chunk) {
# checksum from a string and chunk size (by default 4)
# with chunk==2, this [should be] the RFC1071 Internet Checksum (haven't tested yet)
chunk = (chunk == 0) ? 4 : chunk;
size = length(str);
split(str, chars, "");
sum = 0;
for (i = 1; i <= size; i += chunk) {
cur = 0;
val = _ord_[chars[i]];
for (j = 0; (j < chunk) && ((i + j) <= size); j++) {
cur += lshift(val, 8 * j);
}
sum += cur;
}
return compl(sum);
}
BEGIN {_ord_init()}