Wednesday 4 September 2013

PRINT BINARY DATA IN C

PRINT BINARY DATA IN C
==============================================


/*** This Program Can Print Binary Data as hex string in to
 * stdout or any stream by simple modification.
 * Date: 04/09/2013
 * Author: Rajesh kumar Sahoo.
 * File Name: binprinter.c
 */

#include <stdio.h>
/**
 * This is the main function designed to print binary data.
 */
int print_bin_data(const void *bin_buf,const int len)
{
        int i;
        unsigned char uch;
        const char *buf;
        buf = (const char *) bin_buf;
        for(i=0;i<len;i++){
                uch = buf[i];
                fprintf(stdout,"%02X",uch); // change stdout to required stream
        }
        printf("\n");
}

int main(int argc, char *argv[])
{
        short int ssL_num_one=-1;
        int siL_num=100;
        long int slL_num_two=2000;
        float fL_float_one=10.056;
        printf("short %d in memory as: ",ssL_num_one);
        print_bin_data(&ssL_num_one, sizeof(ssL_num_one));
        printf("integer %d in memory as: ",siL_num);
        print_bin_data(&siL_num, sizeof(siL_num));
        printf("long %ld in memory as: ",slL_num_two);
        print_bin_data(&slL_num_two, sizeof(slL_num_two));
        printf("float %f in memory as",fL_float_one);
        print_bin_data(&fL_float_one, sizeof(fL_float_one));
        return 0;
}

:::::::compile and executing::::::::::

$ gcc binprinter.c -o bin_print
$./bin_print

:::::::output::::

short 10 in memory as: FFFF
integer 100 in memory as: 64000000
long 2000 in memory as: FFFFFFD0070000
float 10.056000 in memory as60FFFFFFE52041