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

From: Unforgiven (jaapd3000_at_hotmail.com)
Date: 05/26/04


Date: Wed, 26 May 2004 00:37:36 +0200

ckroom wrote:
> 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::ostream_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.

-- 
Unforgiven 


Relevant Pages

  • Re: Hex to bin
    ... > What would be the best way to convert Hex to bin? ... chars on some machines, in which case you might past the end of the ... To get a binary string representation you write your own function, ... unsigned int number = 800; ...
    (comp.unix.programmer)
  • Re: String to HEX & BIN Conversion?
    ... > salsipius wrote: ... >> I have a char array say ... >> with a space between the 2 HEX numbers that I am trying to read into a ... %x expects unsigned int, which may happen to be the same as ...
    (comp.lang.c)
  • Re: Simple C question...entering binary
    ... Albert van der Horst wrote: ... You can enter the value in hex, octal, or decimal. ...
    (comp.arch.embedded)
  • Re: Non-printable char in regex
    ... I tried using Hex, ... Octal and Control patterns without success. ... chars in the string the subsequent pattern matching works fine. ...
    (comp.lang.perl.misc)
  • Re: Non-printable char in regex
    ... I have a regex problem on Windows XP Active Perl V5.8.8. ... I tried using Hex, ... chars in the string the subsequent pattern matching works fine. ...
    (comp.lang.perl.misc)