C: Power of (^) & hex to dec converter

I have spent almost 2 evenings trying to create a C program to convert Hex (0x) into a decimal number. After re-writing it 3 times, I had figured out the logical structure.

A previous little program I wrote returned the total decimal value of a provided number of bits. For that program, I was able to use:

1 << i;

to provide me with “1 to the power of i”. I couldn’t figure out why this formula didn’t work at all with ^16;  1^16  kept returning a value of  32. I finally gave up and found a different route.

<math.h> gave me a function that returns the value of a powerof equation.

double pow(double x, double y);

You must also include  -lm  flag whilst compiling. After implementing the function, the whole program started returning correct results. Job done. Here’s the code ( if your interested )

hextodec.c

#include <stdio.h>
#include <inttypes.h>
#include <stdint.h>
#include <string.h>
#include <math.h> //use -lm while compile

int main(int argc, char *argv[])
{

printf("\n"); //clean up top

if (argc !=2) //no arguments or too many
 {
 printf("Please provide hex argument (no more then 1)\n\n");
 return 0;
 }
else if (strlen(argv[1]) > 16) // check for no greater then 64bit hex
 {
 printf("Only 64bit hex\n\n");
 return 0;
 }

int num[strlen(argv[1])]; //set num array to the string length

for (int i = 0; i < strlen(argv[1]); i++) //loop arg array to check for invalid input
 {
 int a = argv[1][i]; //set a to current ascii value
 
 if (a >= 48 && a <= 57) num[i] = a - 48; // remove 48 from a to give [0-9] value
 else if (a >= 65 && a <= 70) num[i] = (a - 65) + 10; //capital letters to value
 else if (a >= 97 && a <= 102) num[i] = (a - 97) + 10; //lowercase letters to valu
 else
 {
 printf("Please enter a valid HEX\n\n"); //error return
 return 0;
 }
 }

uint64_t value = 0; //total value
uint64_t temp = 0; //temp value

int hexcounter = (strlen(argv[1])-1); //set hex counter to decrement

for (int i = 0; i < strlen(argv[1]); i++) //loop to calculate values
 {

 temp = (uint64_t)num[hexcounter] * pow(16,i); // 16 to power of i * num
 value = (uint64_t)temp + value; //add new value to total

 hexcounter--; //decrement ascii counter
 }

printf("Value of 0x"); //success and loop to display result
for (int i = 0; i < strlen(argv[1]); i++)
 {
 printf("%c", argv[1][i]); //print original hex argument
 }
printf(" = %" PRIu64 "\n\n", value); //print value
return 1; //return
}

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.