Last active
September 9, 2019 22:52
-
-
Save jstaursky/6a665da886ca5f26d563e4ed6d1a300e to your computer and use it in GitHub Desktop.
Have fun manipulating data on the binary level!
This file contains 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 <stdio.h> | |
#include <stdbool.h> | |
#include <string.h> | |
#include <stdint.h> | |
#include <stdlib.h> | |
#include <inttypes.h> | |
// gcc Print_data_in_binary.c -o printBinary | |
// | |
// ./printBinary 27 | |
// OUTPUTS | |
// Input is 27 | |
// 11011 | |
uintptr_t* createbinrep (uint8_t* input, | |
size_t bsize, // size in bytes | |
bool** brep) | |
{ | |
bool *tmp, *bp; | |
if ((tmp = calloc (8 * bsize, sizeof (bool))) == NULL) { | |
exit (EXIT_FAILURE); | |
} | |
*brep = tmp; | |
bp = *brep; | |
uint8_t* result = calloc (bsize, sizeof (uint8_t)); | |
// Loop operates on byte level. Since x86 is lil-endian, must define an | |
// index that iterates over the array in reverse. | |
ssize_t end = bsize - 1; | |
do { | |
// Loop operates at bit level inside each byte. | |
// Note how bp is not reset between do-while iterations. | |
for (int nbit = 8 - 1; nbit >= 0; --nbit, ++bp) { | |
// Check whether bit "nbit" is 1 or 0. | |
if ((input[end] & (1 << nbit)) != 0) { | |
result[end] |= 1 << nbit; // set bit "nbit". | |
*bp = true; | |
} else { | |
result[end] &= ~(1 << nbit); // set bit "nbit". | |
*bp = false; | |
} | |
} | |
} while (end -= 1, end >= 0); | |
return (uintptr_t*)result; | |
} | |
void binprint (bool* bin, size_t size) | |
{ | |
bool suplead = true; // suppress leading zeros for cleaner output. | |
for (int i = 0; i < (size); ++i) { | |
if (bin[i] == true || suplead == false) { | |
suplead = false; | |
printf ("%i", bin[i]); | |
} | |
} | |
puts (""); | |
} | |
int main (int argc, char* argv[]) | |
{ | |
long input = strtol (argv[1], NULL, 10); | |
printf ("Input is %li\n", input); | |
bool* binput = NULL; | |
long linput = *(long *) createbinrep ((uint8_t*)&input, sizeof (input), &binput); | |
binprint (binput, 8*sizeof(input)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment