Last active
October 13, 2025 08:59
-
-
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
This file contains hidden or 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 <stdbool.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
/* | |
* Print the bits in the 2nd file that are different from the 1st file | |
* | |
* 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 bytenumstr[16], leftstr[16], rightstr[16]; | |
if (sscanf(buf, "%s %s %s", bytenumstr, leftstr, rightstr) != 3) { | |
fprintf(stderr, "unexpected input: %s\n", buf); | |
continue; | |
} | |
// convert byte number to offset | |
int offset = strtol(bytenumstr, NULL, offset_base) - 1; | |
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 diffbit[9] = {'.', '.', '.', '.', '.', '.', '.', '.', '\0'}; | |
char outbit[9] = {'.', '.', '.', '.', '.', '.', '.', '.', '\0'}; | |
for (int i = 0; i < 8; i++) { | |
if ((diff >> i) & 1) { | |
diffbit[7 - i] = (left >> i) & 1 ? '0' : '1'; | |
outbit[7 - i] = diffbit[7 - i]; | |
} else { | |
if ((left >> i) & 1) { | |
outbit[7 - i] = '1'; | |
} | |
} | |
} | |
printf("0x%08X %s %s\n", offset, diffbit, outbit); | |
} | |
exit(EXIT_SUCCESS); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment