Strip parity bits in C -
say have stream of bits 8 bits of data followed 2 parity bits (pattern repeats).
example (x parity bits):
0001 0001 xx00 0100 01xx 0001 0001 xx00 ...
should become
0001 0001 0001 0001 0001 0001 ...
i feel should easy , i'm on thinking it, how go stripping these parity bits?
the tricky bit here c doesn't let work bits easily, bytes. going assume char
holds 8 bits (check char_bit
in limits.h
) -- case on modern systems. least common multiple of 8 , 10 40, want work in buffer of @ least 40 bits can integer arithmetic on whole -- in practice means 64-bit type. here's 1 way it, reading stdin , writing stdout. handling streams not multiple of 40 bits in length left exercise.
#include <stdint.h> #include <stdio.h> int main(void) { int c; uint_least64_t buffer; (;;) { buffer = 0; /* read in 4 10-bit units = 5 8-bit units */ c = getchar(); if (c == eof) break; buffer = ((buffer << 8) | c); c = getchar(); if (c == eof) break; buffer = ((buffer << 8) | c); c = getchar(); if (c == eof) break; buffer = ((buffer << 8) | c); c = getchar(); if (c == eof) break; buffer = ((buffer << 8) | c); c = getchar(); if (c == eof) break; buffer = ((buffer << 8) | c); /* write out non-parity bits */ putchar((buffer & 0xff00000000ull) >> 32); putchar((buffer & 0x003fc00000ull) >> 22); putchar((buffer & 0x00000ff000ull) >> 12); putchar((buffer & 0x00000003fcull) >> 2); } /* deal incomplete block here */ return 0; }
... if wanted clever check parity bits before threw them away, although have come constructive when (not if) checksum failed.
Comments
Post a Comment