C conversions between Hexadecimal and Decimal

Here is some C code I threw together back in 2001 for converting hexadecimal to decimal, and converting decimal to hexadecimal. It isn’t really complex code, unless you need it now and you haven’t done it before. The best use for this code is to compile it and use it as a command line utility with your favorite OS.

For your convenience, here it is.

First, let’s convert decimal to hexadecimal.

#include <stdlib.h>

int main(int argc, char *argv[]) {
  if (argc != 2) {
    printf("nnIncorrect format for dec2hex.");
    printf("ndec2hex [decimal # to convert to hexadecimal]nn");
  }
  else {

    int x = atoi(argv[1]);

    printf("n%Xnn", x);
  }
  return 0;
}

Now, let’s convert hexadecimal to decimal.

#include <stdlib.h>

int main(int argc, char *argv[]) {
  if (argc != 2) {
    printf("nnIncorrect format for dec2hex.");
    printf("ndec2hex [decimal # to convert to hexadecimal]nn");
  }
  else {

    int x = atoi(argv[1]);

    printf("n%Xnn", x);
  }
  return 0;
}