Re: Convert decimal values to hex and put in a string
In article <4fefa858-01af-4835-9a45-cf85fe1f1462@p69g2000hsa.googlegroups.com>,
Angus <anguscomber@gmail.com> wrote:
Hello
I have an unsigned char[14] and I want to convert the individual array
values into hex and copy to a std::string.
The array does not always hold 14 values - but I do know the length of
the data - obviously up to 14 chars.
An example is an array of six items with decimal values: 0, 10, 228,
164, 72, 11. I want to convert these values to hex and copy to a
string. Eg 000AE4A4480B - which the astute might recognise as a MAC
address.
I tried:
unsigned char cval = 10; // A
^^^^
Your main problem. streams print chars as characters.
If you want the stream << operator to treat it as a number
you must give it a number not a char.
std::strstream str;
Use std::stringstream, strstream is deprecated.
str << std::hex << cval << std::endl;
^^^^^^^^^?
You really should put that on std::cout it makes
limited sense on the stringstream here
(unless you are planning to use it as a separator
and append more values)
std::cout << str.str;
^^^^^ that should not compile
str.str() exists.
But that outputs 1 for some reason.
So try:
#include <iostream>
#include <sstream>
int main()
{
unsigned int cval = 42;
std::stringstream str;
str << std::hex << cval ;
std::cout << str.str() <<std::endl;
return 0;
}
If your data come in as chars, you will need to cast
them for the stream operator to use it as integer
str << std::hex << static_cast<unsigned int>(character);