diff options
| author | Louis Burda <quent.burda@gmail.com> | 2021-07-02 21:16:19 +0200 |
|---|---|---|
| committer | Louis Burda <quent.burda@gmail.com> | 2023-02-23 00:55:04 +0100 |
| commit | bda0c09745bb127f9622f8413d91459a33634d94 (patch) | |
| tree | d7692d46c5b694725f4212113db235deecd9f35b | |
| download | bin-bda0c09745bb127f9622f8413d91459a33634d94.tar.gz bin-bda0c09745bb127f9622f8413d91459a33634d94.zip | |
Tool to convert file to bitstream
| -rw-r--r-- | .gitignore | 2 | ||||
| -rw-r--r-- | Makefile | 8 | ||||
| -rw-r--r-- | bitcat.c | 83 |
3 files changed, 93 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..94a873d --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +vgcore* +bitcat diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..476bd96 --- /dev/null +++ b/Makefile @@ -0,0 +1,8 @@ +CFLAGS ?= +LDFLAGS ?= + +all: bitcat + +%: %.c + $(CC) -o $@ $< $(CFLAGS) $(LDFLAGS) + diff --git a/bitcat.c b/bitcat.c new file mode 100644 index 0000000..1d4599f --- /dev/null +++ b/bitcat.c @@ -0,0 +1,83 @@ +#include <stdlib.h> +#include <stdio.h> +#include <string.h> +#include <stdarg.h> + +#define ISFLAG(str, fshort, flong) (!strcmp(str, fshort) || !strcmp(str, flong)) + +const char *usage = "USAGE: bitcat [-s SKIP] [-n COUNT] FILE\n"; + +void +die(const char *fmtstr, ...) +{ + va_list ap; + + va_start(ap, fmtstr); + vfprintf(stderr, fmtstr, ap); + va_end(ap); + + exit(EXIT_FAILURE); +} + +int +main(int argc, const char **argv) +{ + unsigned char byte, bit; + size_t skip, size, pos; + const char *filepath; + char *end; + FILE *f; + int i; + + if (argc <= 1) die(usage); + + filepath = NULL; + size = skip = 0; + for (i = 1; i < argc; i++) { + if (ISFLAG(argv[i], "-s", "--skip")) { + if (i++ == argc - 1) goto missing_arg; + skip = strtol(argv[i], &end, 0); + if (end && *end) goto bad_arg; + } else if (ISFLAG(argv[i], "-n", "--count")) { + if (i++ == argc - 1) goto missing_arg; + size = strtol(argv[i], &end, 0); + if (end && *end) goto bad_arg; + } else if (ISFLAG(argv[i], "-h", "--help")) { + die(usage); + } else if (*argv[i] == '-') { + die("Unknown flag: %s\n", argv[i]); + } else if (filepath) { + die("Too many files specified\n"); + } else { + filepath = argv[i]; + } + } + + if (!filepath) + die("No file specified\n"); + + if (!(f = fopen(filepath, "r"))) + die("Failed to open file\n"); + + if (!size) { + fseek(f, 0, SEEK_END); + size = ftell(f) * 8; + fseek(f, 0, SEEK_SET); + } + + for (pos = 0; pos < size + skip && !feof(f); pos++) { + if (pos % 8 == 0) byte = fgetc(f); + bit = (byte >> (pos % 8)) & 1; + if (pos >= skip) putchar(bit ? '1' : '0'); + } + + fclose(f); + + return EXIT_SUCCESS; + +missing_arg: + die("Flag %s expects an argument\n", argv[i]); + +bad_arg: + die("Argument has unexpected value: %s\n", argv[i]); +} |
