简体   繁体   English

如何获得一个真正的16位值?

[英]how to get a true 16-bit value?

So I'm using an LPC1768 using the mbed interface. 所以我使用的是mbed接口的LPC1768。

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. 打印输出值:2已扩展。

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. 将所有位设置为16位。

0xFFFFFFFE and 0xFFFE are both int constants. 0xFFFFFFFE0xFFFE都是int常量。 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. 前者超出了int的范围,因此溢出到负数(-2),然后将short操作数扩展为int (带符号扩展名),并且比较成功。 The latter is equivalent to the value 65534, which is not equal to -2. 后者等于值65534,不等于-2。

To make the test succeed, cast the literal 0xFFFE to int16_t , which will cause it to overflow to the value -2: 为了使测试成功,投字面0xFFFEint16_t ,这将导致其溢出到值-2:

if (test == static_cast<int16_t>(0xFFFE)) {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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