diff options
author | lns <matzeton@googlemail.com> | 2019-03-10 18:41:31 +0100 |
---|---|---|
committer | lns <matzeton@googlemail.com> | 2019-03-10 18:41:31 +0100 |
commit | 1892cc6ef12ff1648b6adf925a12ce76a2f42cef (patch) | |
tree | 929d94db34b622f22241db545f4536919cba0f6e | |
parent | 517348ba69e23cb3217c51cc988c3e29fa120cf9 (diff) |
textify binary data
Signed-off-by: lns <matzeton@googlemail.com>
-rw-r--r-- | Makefile | 9 | ||||
-rw-r--r-- | textify.c | 87 |
2 files changed, 95 insertions, 1 deletions
@@ -4,7 +4,7 @@ CFLAGS := -O2 -g -Wall -ffunction-sections -fdata-sections -ffast-math -fomit-fr LDFLAGS := RM := rm -rf -TARGETS := aes asciihexer dummyshell suidcmd scrambler +TARGETS := aes asciihexer dummyshell suidcmd scrambler textify ifneq ($(strip $(MAKE_NCURSES)),) TARGETS += gol @@ -41,6 +41,13 @@ scrambler: scrambler.o @echo 'Finished building target: $@' @echo ' ' +textify: textify.o + @echo 'Building target: $@' + @echo 'Invoking: GCC C Linker' + $(CC) $(LDFLAGS) -o "$@" "$<" -lm + @echo 'Finished building target: $@' + @echo ' ' + gol: gol.o @echo 'Building target: $@' @echo 'Invoking: GCC C Linker' diff --git a/textify.c b/textify.c new file mode 100644 index 0000000..05ba849 --- /dev/null +++ b/textify.c @@ -0,0 +1,87 @@ +#include <stdio.h> +#include <stdlib.h> +#include <stdint.h> +#include <string.h> + +#define BYTE_TO_BINARY_PATTERN "%c%c%c%c%c%c%c%c" +#define BYTE_TO_BINARY(byte) \ + (byte & 0x80 ? '1' : '0'), \ + (byte & 0x40 ? '1' : '0'), \ + (byte & 0x20 ? '1' : '0'), \ + (byte & 0x10 ? '1' : '0'), \ + (byte & 0x08 ? '1' : '0'), \ + (byte & 0x04 ? '1' : '0'), \ + (byte & 0x02 ? '1' : '0'), \ + (byte & 0x01 ? '1' : '0') + + +void print_binary_hex(uint8_t *bin, size_t siz) +{ + size_t i; + + for (i = 0; i < siz; ++i) { + printf("%s%02X ", " ", bin[i]); + } + printf("\n"); + for (i = 0; i < siz; ++i) { + printf(BYTE_TO_BINARY_PATTERN " ", BYTE_TO_BINARY(bin[i])); + } + printf("\n"); +} + +ssize_t textify(uint8_t *bin, size_t siz, char *out, size_t outsiz) +{ + size_t i, j; + + if (!bin || !out) + return -1; + + for (i = 0, j = 0; i < siz && j < outsiz / 3; ++i, j += 3) { + uint8_t tmp0 = 32, tmp1 = 64, tmp2 = 64; + + if (bin[i] >= 127 || bin[i] < 32) { + if (bin[i] < 32) + tmp1 = bin[i] + 32; + else if (bin[i] >= 127) { + if (bin[i] < 190) + tmp1 = bin[i] - 63; + else + tmp2 = bin[i] - 63*2; + } + } else { + tmp0 = bin[i]; + } + + out[j+0] = tmp0; + out[j+1] = tmp1; + out[j+2] = tmp2; + } + + return j; +} + +int main(int argc, char **argv) +{ + ssize_t ret; + char outbuf[BUFSIZ] = {0}; + + if (argc != 2) { + printf("usage: %s [DATA]\n", argv[0]); + return 1; + } + + print_binary_hex((uint8_t *)argv[1], strnlen(argv[1], BUFSIZ)); + + ret = textify((uint8_t *)argv[1], strnlen(argv[1], sizeof outbuf / 3), + outbuf, sizeof outbuf); + if (ret < 0) + { + printf("%s: textify failed\n", argv[0]); + return 1; + } + + print_binary_hex((uint8_t *)outbuf, ret); + printf("%s result: '%s'\n", argv[0], outbuf); + + return 0; +} |