Hex 2 Dec

In many programming languages there is built-in command or function to convert a decimal value to a hex value. But at least in BlitzMax there isn’t a command or function to convert a hex value to a dec value. In this post I present my little function to convert a hex value to dec value in BlitzMax and in C.

The BlitzMax function:

First, put somewhere in the beginning of your program line

Const hexes:String = "0123456789ABCDEF"

The function itself:

Function hex2dec:Int(hexvalue:String)

  Local i:Byte, val10:Int, index:Byte, length:Int
  Local char:String

  length = Len(hexvalue)

  For i = 1 To length

    char = Mid$(hexvalue,i,1)
    index = Instr(hexes,char) - 1
    val10 = val10 + (16 ^ (length - i)) * index

  Next

  Return val10

EndFunction

The C version is a complete program that uses its functions:

#include 
#include 
#include 

int hex2dec(char*);
int indexOfchar(char);

const char hexes[] = "0123456789ABCDEF";

void main (void) {

  char hex[8+1];

  printf("Hex number: ");
  scanf("%s",&hex[0]);
  printf("%s is %d in dec.n",&hex[0],hex2dec(&hex[0]));
}

int hex2dec(char *hex) {
  int i, index, val10, length;
  char chr;

  val10 = 0;

  length = strlen(hex);

  for (i = 0; i < length; i++) {
    chr = hex[i];
    index = indexOfchar(chr);
    val10 = val10 + pow(16,(length - i - 1)) * index;
}
  return val10;
}

int indexOfchar(char chr) {

  int i;

  for (i = 0; i < 16; i++) {
    if (hexes[i] == chr) return i;
  }
}

Be careful with the C version: It doesn’t check if the input is correct. As you can see from the code the letters in the hex number should be given in capital letters. Feel free to use and improve these codes!