Imagine that you have read in a hexadecimal string from the command line, a config file or whatever, and you want to use this value in your program. To do this, you need to do a string to integer conversion, but in base 16 since it’s a hexadecimal string.

To do this, you can use the

std::strtoul(<buffer>, <buffer_length>, <base>)

method. This will return a value as an unsigned long. If you need the value as a signed long, you can use std::strtol(...) instead. In both cases, you need to include cstdlib.

If your buffer is NULL terminated, you can pass in a zero value as the buffer_length.

For example:

#include <cstdlib>
#include <iostream> // for std::cout

int main()
{
    char hex_string[] = "0xbeef";
    unsigned long hex_value
        = std::strtoul(hex_string, 0, 16);

    std::cout << "hex value: " << hex_value << std::endl;
    return 0;
}

will print the following:

hex value: 48879

  1. Mikael Svensson says:

    Hey, don’t have a comment on this post in particular, but I just wanted to say that your site rocks!

    Subscribe to it through RSS, and when something gets posted, this is the first I read from my >1000 unread items.

    /Mikael

  2. Pradeep says:

    Is this work on cpp version 8 ?