C -Cuzz by C类型促销从短到INT

发布于 2024-11-05 13:28:47 字数 8 浏览 6 评论 0原文

continue

I have a question that needs guidance from any expert:

  1. As a value with short type is passed as an argument to printf() function, it'll be automatically promoted to int type, that is why the printf() function will see the value as int type instead of short type.

  2. So basically short type is 16-bits wide, which is 0000000000000000 while int type is 32-bits wide, which is 00000000000000000000000000000000.

  3. Let's say I declare a variable call num with short type and initialise it with a value of -32, that means the most significant bits of the short type will be 1, which is 0000000011100000.

  4. When I pass this value to printf(), it'll be converted to int type, so it'll become 00000000000000000000000011100000.

  5. In step 4, when it is converted to int, the most significant bit is 0.

  6. Why, when I use the %hd specifier or even the %d specifier, will it still still prompt me for a negative value instead of a positive?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

琉璃繁缕 2024-11-12 13:28:47

不,short 和 int 都是有符号类型,因此它是通过符号扩展而不是 0 字节填充来提升的:

-32 short =                   11111111 11100000 
-32 int   = 11111111 11111111 11111111 11100000

将 MSB 保留为 1,即负数。

您可以通过先将其强制转换为无符号来伪造您所期望的行为,例如

printf("%d", (unsigned short)((short)(-32)));

No, short and int are both signed types, so it is promoted by sign extension not 0-byte padding:

-32 short =                   11111111 11100000 
-32 int   = 11111111 11111111 11111111 11100000

leaving the MSB as 1 i.e. negative.

You could fake the behavour you're expecting by casting it unsigned first, e.g.

printf("%d", (unsigned short)((short)(-32)));
旧人 2024-11-12 13:28:47

将short 转换为int 基本上是将short 的最高有效位复制到int 的前16 位中。这就是为什么 int 被打印为负数。如果您不希望出现此行为,请使用ushort

Converting a short to an int basically replicates the most significate bit of the short into the top 16 bits of the int. This is why the int is printed as negative. If you do not want this behaviour using a ushort.

多彩岁月 2024-11-12 13:28:47

正如你所说,它是转换的,在这种情况下转换意味着知识。也就是说,编译器知道有符号短整型转换是如何工作的。它不只是在前面附加位,它还会创建一个与 Short 具有相同值的新 int。这就是为什么你会得到正确的数字。

As you say it is converted and conversion in this case implies knowlegde. That is the compiler knows how signed short to int conversion work. It does not just append bits in front, it creates a new int with the same value as the short. That's why you get the correct number.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文