convert hex string to int values in C++

boost::lexical_cast is quite handy to convert between string and numerical types. However, sometimes you need more. for example, when you want to convert a string "0x0A" to its int value 0x0A(10), or vice versa. you are out of luck. The following code comes handy for this purpose.

#pragma once
#include <string>
#include <sstream>
#include <iomanip>

// the following routines convert dec/hex string literal to size_t values

namespace numeric_conversion
{
    template <typename T, bool is_hex>
    size_t string_to_size_t(const std::basic_string<T>& s)
    {
        std::basic_istringstream<T> ss(s, std::ios_base::in);

        size_t size(0);
        ss >> (is_hex ? std::hex : std::dec )>>size;
        return size;
    }

    template <typename T>
    size_t hexstring_to_size_t(const std::basic_string<T>& s)
    {
        return string_to_size_t<T, true>(s);
    }

    template <typename T>
    size_t hexstring_to_size_t(const T* s)
    {
        return string_to_size_t<T, true>(std::basic_string<T>(s));
    }

    template <typename T>
    size_t decstring_to_size_t(const std::basic_string<T>& s)
    {
        return string_to_size_t<T, false>(s);
    }

    template <typename T>
    size_t decstring_to_size_t(const T* s)
    {
        return string_to_size_t<T, false>(std::basic_string<T>(s));

    }

    template <int N>
    std::wstring to_hex_string(size_t i, bool map_0_to_empty)
    {
        if(map_0_to_empty && (0 == i)) return L"";

        std::wstringstream wss;
        wss << L"0x"/*std::showbase*/ << std::hex << std::setw(N) << std::setfill(L'0') << i;

        return wss.str();
    }

}
Test code:
#include <iostream>
int main()
{
	using namespace std;
	using namespace numeric_conversion;
	
	wcout << L"convert string with base: 0x0a = " << hexstring_to_size_t(L"0x0a") << endl;
	wcout << L"convert string with base no base: 0a = " << hexstring_to_size_t(L"0a") << endl;	
	wcout << L"convert value to hex string: 0a = " << to_hex_string<2>(10, true);

}
Output:
image 

Advertisements
Post a comment or leave a trackback: Trackback URL.

Comments

  • Wendi  On May 30, 2014 at 6:20 am

    Write more, thats all I have to say. Literally, it seems as though you relied on the
    video to make your point. You definitely know what youre talking about, why waste your intelligence on just posting videos to your weblog when you could be giving us
    something enlightening to read?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: