打印C中字符变量的整数值(Printing Integer value of character variable in C)

系统教程 行业动态 更新时间:2024-06-14 16:57:17
打印C中字符变量的整数值(Printing Integer value of character variable in C)

最近在我的研究所,我得到了一个代码,并被要求找出答案。 代码看起来像这样。

#include <stdio.h> int main() { char ch=500; printf("%d\n",ch); }

输出将为-12

我的问题是:我如何计算这种代码的值? 是否有任何寻找价值的公式或流程?

Recently in my Institute I was given a code and was asked to find out the answer. The code looks like this.

#include <stdio.h> int main() { char ch=500; printf("%d\n",ch); }

The output will come as -12

My question is: How can I calculate the value for this kind of code? Is there any formula or process for finding the values?

最满意答案

代码在语法上是正确的,但没有按照你的想法做。 正如Paul Hankin建议你的编译器应该给你一个警告,因为你试图设置一个不适合char变量中的char的数字。

char是1个字节,因此如果有符号则可以存储最多127个数字,如果未签名则可以存储255个数字。 该值溢出,仅考虑低8位。

500 = 0b111110100

仅取低8位:0b11110100

MSB为1,因此它为负数。

1补码加1是0b00001100,即12

这就是你得到-12的原因。

用short或int替换它应该正确打印500。

The code is syntactically correct but not doing what you think. As Paul Hankin is suggesting your compiler should give you a warning as you are trying to set a number that does not fit into a char in a char variable.

A char is 1 byte so it can store a number up to 127 if signed or 255 if unsigned. The value overflows and only the lower 8 bits are taken into account.

500 = 0b111110100

Take only the lower 8 bits: 0b11110100

The MSB is 1 so it's negative number.

1-complement plus 1 is 0b00001100 which is 12

That's why you get -12.

Replacing it by a short or an int should correctly print 500.

更多推荐

本文发布于:2023-04-12 20:13:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/77da641758007f87ad7f4030d0fc09f3.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   变量   字符   Printing   character

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!