简体   繁体   English

有符号和无符号,以及C中的位扩展如何工作

[英]Signed and unsigned, and how bit extension works in C

unsigned short s;
s = 0xffff;
int i = s;

How does the extension work here? 扩展如何在这里工作? 2 larger order bytes are added, but I'm confused whether 1's or 0's are extended there. 添加了2个更大的顺序字节,但我很困惑1或0是否在那里扩展。 This is probably platform dependent so let's focus on what Unix does. 这可能与平台有关,所以让我们关注Unix的作用。 Would the two bigger order bytes of the int be filled with 1's or 0's, and why? int的两个更大的顺序字节是用1还是0填充,为什么?

Basically, does the computer know that s is unsigned, and correctly assign 0's to the higher order bits of the int? 基本上,计算机是否知道s是无符号的,并且正确地将0分配给int的高阶位? So i is now 0x0000ffff ? 所以i现在是0x0000ffff Or since ints are default signed in unix does it take the signed bit from s (a 1) and copy that to the higher order bytes? 或者因为ints是在unix中默认签名的,它是从s (a 1)获取有符号位并将其复制到更高阶的字节?

No, an unsigned value is never sign-extended. 不, unsigned值永远不会进行符号扩展。 Upcasting will always pad such a value with zeroes. 上传将始终用零填充这样的值。

More precisely, the unsigned variable represents a particular number, and it will still represent the same number after a cast, provided that is possible in the new format. 更准确地说,无符号变量代表一个特定的数字,并且在演员表之后仍然代表相同的数字,前提是新格式是可能的。

Hexadecimal or no, C (although not C99) and C++ are designed to work in the absence of bits, eg with base-10 numerics. 十六进制或否,C(尽管不是C99)和C ++被设计为在没有位的情况下工作,例如使用基数为10的数字。

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

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