c - 整数向下转换 [英] c - integer downcast
问题描述
关于 C 中的整数向下转换,例如
一个 int 值 000F'E000
向下转换为 short 或 unsigned short 将成为 E000
.short
-> -8192
,unsigned short
-> 57344
,
所以它只是简单地削减比特吗?
那么向上转换呢?例如.int -10
就是ffffff81
,转换成long long
的规则是什么?
@Update
关于upcasting,根据答案我做了一些测试,发现2的补码有以下规则:
<前>签:正 -> 正:添加 0 作为前缀位,负 -> 负:添加 1 作为前缀位,未签名:添加 0 作为前缀位,代码:
//整数,向下转换 &向上,#include void downcastTest() {int i = 127<<13;printf("%X, %hX, %hi\n", i, i, i);}void upcastTest() {国际我= 127;int j = -127;printf("%x, %llx\n", i, (long long)i);printf("%x, %llx\n", j, (long long)j);}int main(int argc, char * argv[]) {downcastTest();upcastTest();返回0;}
Downcasts
转换为较小的整数类型会丢弃目标类型中不存在的最高有效位(最左边,因为您将完整的二进制整数写在纸上).
向上广播
向上转换为更大的整数更复杂:
- 对于无符号到无符号类型,它添加了足够的零最高有效字节;这总是保留价值.
- 对于signed到signed类型,它对源类型进行符号扩展(即用与源的符号位相等的位打包新字节整数);这总是保留价值,正面或负面
- 对于无符号到有符号类型,它有效地添加了足够的零最高有效字节;这总是保留值,因为在向上转换的性质中,目标中总是有更多位,因此总是有额外的符号位"的空间
- 对于signed 到unsigned 类型,它进行符号扩展,然后强制转换;这不能始终保留该值,因为无法表示负值.
About integer numbers downcasts in C, e.g.
An int value 000F'E000
downcast to short or unsigned short will become E000
.
short
-> -8192
,
unsigned short
-> 57344
,
So does it simply cut the bits?
And what about upcasts? E.g. int -10
is ffffff81
, what is the rule to cast to long long
?
@Update
About upcasting, according to the answers I did some tests and found that with 2's complement it has the following rules:
signed: positive -> positive: add 0 as prefix bits, negative -> negative: add 1 as prefix bits, unsigned: add 0 as prefix bits,
code:
// integer numbers, downcast & upcast,
#include <stdio.h>
void downcastTest() {
int i = 127<<13;
printf("%X, %hX, %hi\n", i, i, i);
}
void upcastTest() {
int i = 127;
int j = -127;
printf("%x, %llx\n", i, (long long)i);
printf("%x, %llx\n", j, (long long)j);
}
int main(int argc, char * argv[]) {
downcastTest();
upcastTest();
return 0;
}
Downcasts
A cast to a smaller integer type discards the most significant (left-most as you'd write the full binary integer on paper) bits that are not present in the destination type.
Upcasts
An upcast to a larger integer is more complex:
- For unsigned to unsigned types, it adds sufficient zero most-significant bytes; this always preserves the value.
- For signed to signed types, it sign-extends the the source type (i.e. packs the new byte(s) with bits equal to the sign bit of the source integer); this always preserves the value, positive or negative
- For unsigned to signed types, it effectively adds sufficient zero-most significant bytes; this always preserves the value, as in the nature of an upcast, there are always more bits in the destination, so there is always space for an extra sign 'bit'
- For signed to unsigned types, it sign-extends, then casts; this cannot always preserve the value, as a negative value cannot be represented.
这篇关于c - 整数向下转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!