Skip to content

Instantly share code, notes, and snippets.

@masterl
Created June 2, 2017 05:01
Show Gist options
  • Save masterl/0e67bb2ab9cf5f1f8bd20f94c1b81dc2 to your computer and use it in GitHub Desktop.
Save masterl/0e67bb2ab9cf5f1f8bd20f94c1b81dc2 to your computer and use it in GitHub Desktop.
Integer (int) binary visualization fun
#include <stdio.h>
#include <stdlib.h>
char *int_binary_to_str( int const value );
void test_int( int const value );
int main( void )
{
test_int( 5 );
test_int( 0xF18 );
return 0;
}
void test_int( int const value )
{
char *bits_str;
bits_str = int_binary_to_str( value );
if( bits_str )
{
puts( "" );
printf( " int: %d\n", value );
printf( "hexadecimal: %X\n", value );
printf( " binario: " );
puts( int_binary_to_str( value ) );
free( bits_str );
}
}
char *int_binary_to_str( int const value )
{
unsigned const BITS_ON_BYTE = 8;
unsigned const bits_str_capacity = sizeof( int ) * BITS_ON_BYTE + 1;
char *bits_str = malloc( sizeof( char ) * bits_str_capacity );
bits_str[bits_str_capacity - 1] = '\0';
unsigned int mask = 1;
unsigned int test;
for( int offset = bits_str_capacity - 2; offset >= 0; --offset )
{
test = value & mask;
bits_str[offset] = test ? '1' : '0';
mask <<= 1;
}
return bits_str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment