how to get a true 16-bit value?


So I'm using an LPC1768 using the mbed interface.

This snippet:

int16_t test = -1;
test -= 1;
printf("Value: %d\n", sizeof(test));
if (test== 0xFFFE) {
    printf("It's stayed the same.\n");
} else if (test== 0xFFFFFFFE) {
    printf("It's been extended.\n");
} else {

prints out Value: 2 It's been extended.

How could I modify this so that it will print "It's stayed the same."? The goal is to have

int16_t test = -1

make test be a 16 bit value with all bits set.

asked on Stack Overflow Apr 20, 2017 by plsplox • edited Apr 20, 2017 by Robert Harvey

1 Answer


0xFFFFFFFE and 0xFFFE are both int constants. The former is out of range of int so it overflows into the negative (-2), then the short operand is widened to int (with sign extension) and the comparison succeeds. The latter is equivalent to the value 65534, which is not equal to -2.

To make the test succeed, cast the literal 0xFFFE to int16_t, which will cause it to overflow to the value -2:

if (test == static_cast<int16_t>(0xFFFE)) {
answered on Stack Overflow Apr 20, 2017 by cdhowie

User contributions licensed under CC BY-SA 3.0