Convert hex string to unsigned char in C ++

I want to convert a hexadecimal representation into a string into an unsigned char variable as follows:

std::stringstream ss;
uint8_t x;
ss << "1f";
ss >> std::hex >> x;  // result: x = 0x31 (=49 in decimal and ='1' as char)

Obviously, I assumed that the conversion would result in x = 0x1f (= 31 in decimal), since 0x1f is less than 0xff, which is the maximum that can be stored in an unsigned char with 8 bits. Instead, what happened was that only the first 8 bits of my string were used in the conversion.

Can someone explain to me exactly why this happened and how to fix it?

+4
source share
1 answer

std::uint8_t ( , . ) unsigned char, operator>> , . - '1' x, ASCII 49. , ASCII '1' , , ; "1e" "10" "1xyz" x == 49.

, , 8 :

std::stringstream ss;
uint8_t x;
unsigned tmp;

ss << "1f";
ss >> std::hex >> tmp; 
x = tmp;                // may need static_cast<uint8_t>(tmp) to suppress
                        // compiler warnings.

( )

, uint8_t (!) , , 8 , . ++ C [cstdint.syn]/2, C99 7.18.1.1:

1 typedef intN_t N, . , int8_t 8 .

2 typedef uintN_t N. , uint24_t 24 .

3 . , 8, 16, 32 64 , typedef.

- . - , 8 , , PDP ( , UNIVACs 1). , , C , , , , , C , C.

8- , unsigned char, , 8 , 8 , , 2 uintN_t , . , . , , , .

, : uint8_t, ++, . , uint8_t , unsigned char, .

, , . ++, , uint8_t unsigned char. 3

1 , , C Setun ( ).

2 , .

3 , , , . , , , .

+7