Parsing hex and decimal numbers in C++11 The function arg_to_uint64 takes a 0-terminated string and returns an unsigned int. The unsigned int is the integer presentation of arg in decimal or in hex (if prefixed with 0x) as defined in the C language standard.

constexpr char hexprefix[]="0x";

inline std::uint64_t
arg_to_uint64(const char* arg)
{
   constexpr std::size_t hexprefix_len=sizeof(hexprefix)-1;
   bool is_hex=std::strncmp(arg,hexprefix,hexprefix_len)==0;
   int base;

   if(is_hex)
   {
      arg+=hexprefix_len;
      base=16;
   }
   else
      base=10;

   std::size_t idx;
   std::uint64_t r=std::stoull(arg,&amp;idx,base);

   if(idx!=std::strlen(arg))
      throw std::runtime_error("garbage at the end of input");
   return r;
}


Is there a better/shorter way to do this? My platform is Linux.



This is my improved code as described in the answer from William Morris:

inline std::uint64_t
arg_to_uint64(const char* arg)
{
   std::size_t idx;
   std::uint64_t r=std::stoull(arg,&amp;idx,0);

   if(arg[idx]!='\x0')
      throw std::runtime_error("garbage at the end of input");
   return r;
}
Just use strtoll with a base of 0