简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM