Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stringstream >> uint8_t in hex? c++

i am confused by the output of the following code:

uint8_t x = 0, y = 0x4a;
std::stringstream ss;
std::string a = "4a";


ss << std::hex << a;
ss >> x;

std::cout << (int)x << " "<< (int)y << std::endl;
std::cout << x << " "<< y <<std::endl;
std::cout << std::hex << (int)x <<  " " << (int)y << std::endl;

uint8_t z(x);
std::cout << z;

the output for the above is:

52 74

4 J

34 4a

4

and when we change replace the first line with:

uint16_t x = 0, y = 0x4a;

the output turns into:

74 74

74 74

4a 4a

J

I think i understand what happens but i don't understand why it happens or how i can prevent it/work around it. From my understanding std::hex modifier is somehow undermined because of the type of x, maybe not exactly true at a technical level but it simply just writes the first character it reads.

Background: The input is supposed to be a string of hexadecimal digits, each pair representing a byte( just like a bitmap except in string). I want to be able to read each byte and store it in a uint8_t so i was experimenting with that when i came across this problem. I still can't determine what's the best method of this so if you think what i'm doing is inefficient or unnecessary i would appreciate to know why. Thank you for reading,

like image 787
user3402183 Avatar asked Oct 31 '22 17:10

user3402183


1 Answers

ss >> x

is treating uint8_t x as an unsigned char. The ascii value of '4' is (decimal) 52. It's reading the first char of the string "4a" into x as if x were a character. When you switch it to uint16_t, it's treating it as an unsigned short integer type. Same with y.

like image 187
Dmitry Rubanovich Avatar answered Nov 08 '22 07:11

Dmitry Rubanovich