Skip to content

Instantly share code, notes, and snippets.

@ph1ee
Last active June 18, 2020 13:37
Show Gist options
  • Save ph1ee/83091d030db47d25f8d4a6def94c4eee to your computer and use it in GitHub Desktop.
Save ph1ee/83091d030db47d25f8d4a6def94c4eee to your computer and use it in GitHub Desktop.
inspired by hexcmp, bitcmp is a tool to view `cmp -l` output in bitwise form
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
/*
* E.g.,
* cmp -l <(dd if=/dev/urandom count=1) \
* <(dd if=/dev/urandom count=1) \
* | bitcmp -o
*/
int main(int argc, char *argv[]) {
int value_base = 10;
int offset_base = 10;
bool inverse = false;
for (int opt; (opt = getopt(argc, argv, "oOxXv")) != -1;) {
switch (opt) {
case 'o':
value_base = 8;
break;
case 'O':
offset_base = 8;
break;
case 'x':
value_base = 16;
break;
case 'X':
offset_base = 16;
break;
case 'v':
inverse = true;
break;
default:
fprintf(stderr, "usage: %s [OPTION]...\n", argv[0]);
exit(EXIT_FAILURE);
}
}
for (char buf[256]; fgets(buf, sizeof(buf), stdin);) {
char offsetstr[16], leftstr[16], rightstr[16];
if (sscanf(buf, "%s %s %s", offsetstr, leftstr, rightstr) != 3) {
fprintf(stderr, "unexpected input: %s\n", buf);
continue;
}
int offset = strtol(offsetstr, NULL, offset_base);
int left = strtol(leftstr, NULL, value_base);
int right = strtol(rightstr, NULL, value_base);
if (inverse) {
int tmp = right;
right = left;
left = tmp;
}
if (left < 0 || left > 0xFF || right < 0 || right > 0xFF) {
fprintf(stderr, "unexpected input: %s\n", buf);
continue;
}
int diff = left ^ right;
char oct[9] = {'.', '.', '.', '.', '.', '.', '.', '.', '\0'};
for (int i = 0; i < 8; i++) {
if ((diff >> i) & 1) {
oct[7 - i] = (left >> i) & 1 ? '0' : '1';
}
}
printf("0x%08X %s\n", offset, oct);
}
exit(EXIT_SUCCESS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment