-9

I need to build a function, my input is a char *string and I'll need to get the "same representation" but in a uint16.

For example:

input: "12"  -->  output: 0x0012
input: "0"   -->  output: 0x0000
input "123"  -->  output: 0x0123
input "1234" -->  output: 0x1234

PD: I can't use "official functions" such as strtol, sscanf...

menchopez
  • 65
  • 2
  • 7

1 Answers1

2

How about this?

#include <stdio.h>
#include <stdint.h>

unsigned int
trans(unsigned char c){
  if ('0' <=c && c <= '9') return c - '0';
  if ('A' <=c && c <= 'F') return c - 'A' + 0x0A;
  if ('a' <=c && c <= 'f') return c - 'a' + 0x0A;
  return 0;
}

uint16_t
hex_to_uint16(const char* s) {
  uint16_t v = 0;
  while (*s)
    v = (v << 4) + trans(*s++);
  return v;
}

#include <assert.h>

int
main(int argc, char* argv[]) {
  assert(0x0012 == hex_to_uint16("12"));
  assert(0x0000 == hex_to_uint16("0"));
  assert(0x0123 == hex_to_uint16("123"));
  assert(0x1234 == hex_to_uint16("1234"));
  assert(0xffff == hex_to_uint16("ffff"));
  return 0;
}
mattn
  • 7,571
  • 30
  • 54