I am converting all binary numbers stored in a file to hexadecimal. The file is parsed through command line argument, but to convert it to hexadecimal I want it to be converted to an integer, i.e. literal integer of the string received and atoi()
doesn't seem to work.
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
int main ( int argc, char *argv[] )
{
FILE *fp,*op;
fp = fopen(argv[1],"r");
op= fopen(argv[2],"w+");
if( fp == NULL)
{
perror("An error has occurred\n");
exit(1);
}
char buff[1026];
unsigned char hexstr[1024];
unsigned long int hexnum,hexint;
unsigned char four[4];
int i, j,len;
while(fgets(buff, sizeof(buff), fp))
{
printf("\nString value = %s", buff);
hexint=atoi(buff);
printf("%ld",hexint);
}
fclose(fp);
fclose(op);
return 0;
}
input file contains:
0000000000001010
1010000000000000
101010111100110111101111
000100100011010001010110
000100010001000100010001
011101110111011101110111
000000000000000000000000
output file should contain:
000a
a000
abcdef
123456
111111
777777
000000
The atoi
function expects the input text to be in decimal format, but you're feeding it binary. Also, you're using the %d
format specifier to print, which output decimal format.
You need to use the strtoul
function for the conversion instead and specify base 2 for the input. Then for the output, use the %x
format specifier to print in hex.
while(fgets(buff, sizeof(buff), fp))
{ printf("\nString value = %s", buff);
hexint=strtoul(buff, NULL, 2);
printf("%lx",hexint);
}
If you want the number of digits printed to vary based on the length of the input text, you can specify a field width of *
and pass the number of digits as an extra parameter, and also add the 0
flag to pad on the left with zeros.
Since you have the binary string, and there are 4 binary digits to 1 hex digits, divide the length of the binary string by 4 and round up to get the number of digits:
hexint=strtoul(buff, NULL, 2);
int bindigits = strlen(buff);
int hexdigits = (bindigits % 4 == 0) ? bindigits / 4 : bindigits / 4 + 1;
printf("%0*lx", hexdigits, hexint);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments