char[] = "FFFFFF" to 3 unsigned char.

C

ckroom

Hi, I have a vector of chars: "FFFFFF"
Each 2 chars from the vector in hex represents a decimal number, how can I
convert the vector to 3 decimal values (char *)"FF"->(int)256. I have no
idea.

Thanks!
 
U

Unforgiven

ckroom said:
Hi, I have a vector of chars: "FFFFFF"
Each 2 chars from the vector in hex represents a decimal number, how
can I convert the vector to 3 decimal values (char *)"FF"->(int)256.
I have no idea.

I used the hex value "abcdef" because it demonstrates the meaning more
clearly.
-----

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>

int main()
{
std::string s = "abcdef";
std::istringstream iss(s);
unsigned int n;
iss >> std::hex >> n;
std::vector<unsigned int> result;
while( n > 0 )
{
result.push_back(n & 0xFF);
n >>= 8;
}

std::cout << std::hex;
std::copy(result.begin(), result.end(), std::eek:stream_iterator<unsigned
int>(std::cout, "\n"));

return 0;
}
-----

After this result[0] contains 0xEF, result[1] contains 0xCD and result[2]
contains 0xAB.

So the output is:
ef
cd
ab

Hope this helps you.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top