Hexadecimal input and output problems

I am having some problems with handling hexadecimals.

I first want to input a string, then get individual chars of the hex values in the string.

Thus, if 'C7E9' is the input I want to get the individual values C7 (199) and E9 (233) from the string. My current dysfunctional code is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main()
{
    int h1, h2;
    string hexinput;
    
    cout << "Hex:";
	cin >> hexinput;

    stringstream ss_h;   
     
    ss_h << hexinput[0] + hexinput[1];
    ss_h >> hex >> h1;
    cout << hexinput[0] << hexinput[1] << " >> hex >> " << +h1;
    
    ss_h << hexinput[2] + hexinput[3];
    ss_h >> h2;

    cout << hexinput[2] << hexinput[3] << " >> hex >> " << +h2;

    // Perform addition of h1 and h2 and then use them as unsigned chars here.
}


So my question is: How to do this properly?
Why do you add them? 'C' + '7' = 67 + 55 = 122.
You know how to put the two chars into cout, so why not do the same for ss_h?
1
2
ss_h << hexinput[0] << hexinput[1];
ss_h >> hex >> h1;
should work. Another way is to read the whole thing first, and only then split it.
1
2
3
4
5
ss_h << hexinput;
int h;
ss_h >> hex >> h;
h1 = h >> 8;
h2 = h & 0xFF;
You could even do this without a stringstream.
Why do you assume that each hex numeral consists of two characters of the string?
then get individual chars of the hex values in the string.

The values of the individual hex characters in the (hex) string 'C7E9' are;
C = 49152
7= 1792
E= 224
9= 9
-------------
51177
-------------
So.....oxC7E9=51177 or am I missing something?
I assume he wants to get the high and low bytes.
How do we get high and low bye ?
High byte is the one with most significant digits, low byte is the one with less significant ones.
Normally if you have a word (2 bytes) X, high byte is X >> 8 and low byte is X & 0xFF.
Topic archived. No new replies allowed.