site  contact  subhomenews

bitflip toggles all bits in a pipe

August 28, 2019 — BarryK

I posted yesterday about an enhancement to EasyDD, verification of write to Flash drive, by writing the "reverse" of the image file, verify, then write the normal image file and verify:

http://bkhome.org/news/201908/easydd-now-verifies-write.html

A very interesting part of the exercise was 'bitflip'. This reads from stdin, writes to stdout, and reports total number of bytes written to stderr on completion. See the link, to acknowledge "goldilocks", the chap who wrote it. Here is the code:

// ref: https://unix.stackexchange.com/questions/104585/bit-wise-complement-with-dd
// pipe in and pipe out. flips every bit.

#include <stdio.h>
#include <unistd.h>
#include <inttypes.h>

#define BUFSZ 4096

int main (void) {
unsigned char buffer[BUFSZ];
int i, check;
uint64_t total = 0;

while ((check = read(0, buffer, BUFSZ)) > 0) {
for (i = 0; i < check; i++) buffer[i] = ~buffer[i];
write(1, buffer, check);
total += check;
}

fprintf(stderr, "bitflip processed %lu bytes.\n", total);
return 0;
}

Simple to compile:

# gcc -o bitflip bitflip.c

The source is in pup-tools-20190828.tar.gz:

http://distro.ibiblio.org/easyos/source/alphabetical/p/

Here is the PET package, actually compiled in Pyro, works fine in Buster:

http://distro.ibiblio.org/easyos/amd64/packages/pet/pet_packages-buster/pup-tools-20190828-pyro64.pet 

Tags: easy