Problem with conversion to hex string.
Can anyone see why this code produces the string "0" when 0x00 is plugged into
it instead of 0x00.
It works fine with 0xff for example.
Code:
template <typename CT, typename T> //PARAMETERIZED OVER CHARACTER AND NUMERIC TYPE TO BE CONVERTED
std::basic_string<CT> CONVERT_TO_STRING(const T& t, std::ios_base & (*f)(std::ios_base&), const std::streamsize precision)
{
std::basic_ostringstream<CT> oss;
oss.setf(std::ios::showbase);
oss <<std::fixed<<std::setprecision(precision)<< f << t;
return oss.str();
};
CONVERT_TO_STRING<char>(0x00, std::hex, 0)
Re: Problem with conversion to hex string.
Do you have an example where the code works? Try passing in 0x1A.
Kuphryn
Re: Problem with conversion to hex string.
The code works for any number but zero.
So I was wondering if there is a known problem with 0, or if I am doing something stupid
Re: Problem with conversion to hex string.
My guess would be that 0x00 is interpreted simply as 0 which can be treated as a NULL pointer, a character, an integer, etc.... Thus you would need some way to disambiguate 0x00. I would try "0x00L".
Re: Problem with conversion to hex string.
If this is VC++ 6.0, the problem is found deep in the source code (the streams ultimately call sprintf()):
Code:
// In the runtime function OUTPUT.C
//.....
/* 4. Check if data is 0; if so, turn off hex prefix */
if (number == 0)
prefixlen = 0;
That is the problem. Before this code is executed, prefixlen is 2.
Souldog, see if you can try your code on another compiler to see if the behavior is the same.
Regards,
Paul McKenzie
Re: Problem with conversion to hex string.
Code:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
main () {
cout << hex << setw(2) << setfill('0') << 0x00 << endl;
cout << hex << setw(2) << setfill('0') << 0x07 << endl;
cout << hex << setw(2) << setfill('0') << 0xFF << endl;
}
This code prints:
00
07
ff
Try using setw and setfill instead of setprecision.
Re: Problem with conversion to hex string.
First thanks for all the responses.
Paul, the same thing happens with Dev-C++ which is gcc.
Thingol, I will try that.
Re: Problem with conversion to hex string.
Souldog,
I am not surprised. The conversion to hex is done precisely as if it
were done by 'printf'. Since 'printf' never prepends 0 with 0x, neither
does the ostream. The C Standard says that only a non-zero value will
be prefixed with 0x. If you want _all_ values to be prefixed, you should
(a) drop the 'showbase' and (b) add "0x" for the hex.
Re: Problem with conversion to hex string.
Yah it looks like I am going to have to write a special function for this. Thanks everyone.....
Heck maybe I can live with 00 instead of 0x00. :)