Luiz
Luiz

Reputation: 148

Cast to right operand of extraction operator (>>)

I couldn't find anyone with a similar problem so I decided to create a new question.

I am currently trying to extract hexadecimal 1 byte sized values from a string stream, I plan on storing the value extracted inside an unsigned char, the problem is, the string stream will extract a single character from the stream and store it in my variable. That's understandable, I thought, as I successfully used a short integer to extract my value and it worked flawlessly. Now that I knew my problem, I thought I could simply cast my variable to a numerical value, while keeping it as an unsigned char, but apparently it wasn't possible for me to cast it as the right operand of the extraction operator:

Note: byte is a typedef for unsigned char, not std::byte.

Here are some attempts:

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5

I'm fine using a short instead of a char, but I wanted to know if there's a way around this, using member operator>>() didn't work for me either!

Edit: This is how my stringstream string looks like: "11 A7 D9 13 6D 9D ED DA FD F4 F1". I want to extract the hexadecimal 11 (17 decimal) into my byteBuffer variable.

Upvotes: 0

Views: 199

Answers (1)

Jarod42
Jarod42

Reputation: 217810

You have to read both characters and do the conversion. You might create a class to handle it, something like:

struct Byte
{
    std::uint8_t c;  
};

std::istream& operator >> (std::istream& is, Byte& b)
{
    unsigned int n;
    is >> std::hex >> n;
    b.c = n;
    return is;
}

Demo

Upvotes: 1

Related Questions