Created
June 2, 2017 04:59
-
-
Save masterl/3e3a0f44ccb6a0cc16a2938e6366448a to your computer and use it in GitHub Desktop.
In-Memory binary visualization fun
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 <stdbool.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
char *binary_as_string( void const *data, size_t data_size ); | |
void write_byte_to_string( char *str, unsigned char const *byte ); | |
void test_int( int const value ); | |
void test_char( char const value ); | |
void test_float( float const value ); | |
int main( void ) | |
{ | |
test_int( 0xA9 ); | |
test_int( 1500239100 ); | |
test_char( 'a' ); | |
test_char( 'D' ); | |
test_float( 37.5 ); | |
test_float( 5000004234.234 ); | |
return 0; | |
} | |
void test_int( int const value ) | |
{ | |
char *bits; | |
bits = binary_as_string( &value, sizeof( value ) ); | |
if( bits ) | |
{ | |
printf( "Representacao binaria em memoria do int %d (hexadecimal: 0x%X)\n", value, value ); | |
printf( "%s\n", bits ); | |
free( bits ); | |
} | |
} | |
void test_char( char const value ) | |
{ | |
char *bits; | |
bits = binary_as_string( &value, sizeof( value ) ); | |
if( bits ) | |
{ | |
printf( "Representacao binaria em memoria do char %c (hexadecimal: 0x%X)\n", value, value ); | |
printf( "%s\n", bits ); | |
free( bits ); | |
} | |
} | |
void test_float( float const value ) | |
{ | |
char *bits; | |
bits = binary_as_string( &value, sizeof( value ) ); | |
if( bits ) | |
{ | |
printf( "Representacao binaria em memoria do float %f\n", value ); | |
printf( "%s\n", bits ); | |
free( bits ); | |
} | |
} | |
char *binary_as_string( void const *data, size_t data_size ) | |
{ | |
unsigned const BITS_ON_BYTE = 8; | |
char *bits_str; | |
unsigned const bits_str_capacity = data_size * BITS_ON_BYTE + 1; | |
unsigned char *data_byte = (unsigned char *)data; | |
unsigned bits_written = 0; | |
bits_str = malloc( sizeof( char ) * bits_str_capacity ); | |
if( !bits_str ) | |
{ | |
return NULL; | |
} | |
bits_str[bits_str_capacity - 1] = '\0'; | |
do | |
{ | |
write_byte_to_string( bits_str + bits_written, data_byte ); | |
bits_written += 8; | |
++data_byte; | |
} while( data_byte != data + data_size ); | |
return bits_str; | |
} | |
void write_byte_to_string( char *str, unsigned char const *byte ) | |
{ | |
unsigned mask = 1; | |
unsigned test; | |
for( int offset = 7; offset >= 0; --offset ) | |
{ | |
test = ( *byte ) & mask; | |
str[offset] = test ? '1' : '0'; | |
mask <<= 1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment