Can std::hex input format support negtive int16_t hex string with two's complement notation such as `ffff` for `-1`?

169 Views Asked by At

I would like to input a text string ffff to a int16_t, the value should be -1.

Here is a simple test C++ program:

#include <iostream>
#include <iomanip>
#include <stdint.h>

int main() {
    int16_t num;

    std::cout << "Enter a hexadecimal number: ";
    std::cin >> std::hex >> num;

    std::cout << "Decimal representation: " << num << std::endl;

    return 0;
}

Here is the result of the program:

Enter a hexadecimal number: ffff
Decimal representation: 32767

You see, the result value 32767 is the largest value of int16_t.

So, my guess is that the line std::cin >> std::hex >> num; does not support the Two's complement notation of the hex format?

1

There are 1 best solutions below

1
Caleb.Steinmetz On

Also, to get around this, you can just turn num into a uint16_t and then cast num as a int16_t when you use it.

uint16_t num;
std::cin >> std::hex >> num;
std::cout << (int16_t)num;
return 0;