Saturday, April 02, 2005

Hexadecimal Conversion in C++

Converting from a decimal to a hexadecimal string and back again is actually quite a tedious process and despite the fact it seems basic and fundamental there is actually not much support for it in C++ libraries. ATL server has a couple of functions ATLHexEncode() and ATLHexDecode. They take an array of BYTEs as the decimal input. I have also discovered a couple of neat but more limited implementations. Here they are

Decimal to Hex

                int number = boost::lexical_cast<int>(sNumber);
                std::string s = boost::str( boost::format("%x") % number );

Hex to Decimal

                std::string h(sHexNumber);
                std::istringstream is(h);
                unsigned long d;
                is >> std::hex >> d;
                sDecimal = boost::lexical_cast<std::string>(d).c_str();

No comments: