3
\$\begingroup\$

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,&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,&idx,0);

   if(arg[idx]!='\x0')
      throw std::runtime_error("garbage at the end of input");
   return r;
}
\$\endgroup\$
0

1 Answer 1

6
\$\begingroup\$

Just use strtoll with a base of 0

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.