bin

Bit stream reader / writer
git clone https://git.sinitax.com/sinitax/bin
Log | Files | Refs | LICENSE | sfeed.txt

commit bda0c09745bb127f9622f8413d91459a33634d94
Author: Louis Burda <quent.burda@gmail.com>
Date:   Fri,  2 Jul 2021 21:16:19 +0200

Tool to convert file to bitstream

Diffstat:
A.gitignore | 2++
AMakefile | 8++++++++
Abitcat.c | 83+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
3 files changed, 93 insertions(+), 0 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -0,0 +1,2 @@ +vgcore* +bitcat diff --git a/Makefile b/Makefile @@ -0,0 +1,8 @@ +CFLAGS ?= +LDFLAGS ?= + +all: bitcat + +%: %.c + $(CC) -o $@ $< $(CFLAGS) $(LDFLAGS) + diff --git a/bitcat.c 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]); +}