hex ascii to unsigned long

Convert a hex ascii string into an unsigned long. The ascii string may have an optional leading "0x". The conversion ends when a non-hex character is encountered.

Download hatol.zip

Synopsis:

hatol.cpp


hatol.cpp

Synopsis
#include "utx.h"

unsigned long hatol(char *s)
  {
  if (s == 0) return 0;
  if (*s && *s == '0' && *(s + 1) && (*(s+1) == 'x' || *(s+1) == 'X'))
    s += 2;

  unsigned long d;
  unsigned l;
  for(l = 0; *s ; ++s)
    {
    if (*s >= '0' && *s <= '9')
      d = *s - '0';
    else if (*s >= 'a' && *s <= 'f')
      d = *s - 'a' + 10;
    else if (*s >= 'A' && *s <= 'F')
      d = *s - 'A' + 10;
    else
      break;
    l = (l << 4) + d;
    }

  return l;
  }


TEST(hatol_simple)
  {
  utxassert(hatol(0), 0UL);
  utxassert(hatol(""), 0UL);

  utxassert(hatol("0x0"), 0UL);
  utxassert(hatol("0x1"), 1UL);
  utxassert(hatol("0x01"), 1UL);

  utxassert(hatol("0X0"), 0UL);
  utxassert(hatol("0X1"), 1UL);
  utxassert(hatol("0X01"), 1UL);

  //same thing except no leading '0x'
  utxassert(hatol("0"), 0UL);
  utxassert(hatol("1"), 1UL);
  utxassert(hatol("01"), 1UL);
  }

TEST(hatol_gt10)
  {
  utxassert(hatol("0xA"), 10UL);
  utxassert(hatol("0x0A"), 10UL);
  utxassert(hatol("0xF"), 15UL);
  utxassert(hatol("0x0F"), 15UL);

  utxassert(hatol("0xa"), 10UL);
  utxassert(hatol("0x0a"), 10UL);
  utxassert(hatol("0xf"), 15UL);
  utxassert(hatol("0x0f"), 15UL);
  }

TEST(hatol_max)
  {
  utxassert(hatol("0xFFFFFFFF"), 0xFFFFFFFFUL);
  }
   
TEST(hatol_overflow)
  {
  utxassert(hatol("0x10000000"), 0x10000000UL);
  utxassert(hatol("0x100000000"), 0x00000000UL);
  utxassert(hatol("0x100000001"), 0x00000001UL);
  }

TEST(hatol_otherchars)
  {
  utxassert(hatol("0xFFXFFFFF"), 0xFFUL);
  utxassert(hatol("X"), 0UL);
  }






Contact me about content on this page using john_web-at-arrizza-dot-com
For Web Master or site problems contact: webadmin-at-arrizza-dot-com
Copyright John Arrizza (c) 2001,2002,2003,2004,2005,2006,2007