plsplox
plsplox

Reputation: 179

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 {
    printf("None\n");
}

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.

Upvotes: 0

Views: 392

Answers (1)

cdhowie
cdhowie

Reputation: 169038

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)) {

Upvotes: 2

Related Questions