如何从int分配到char在C工作? [英] How assignment from int to char works in C?

查看:104
本文介绍了如何从int分配到char在C工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您分配一个int在C一个字符会发生什么?它始终只是左侧忽略额外的位?

What happens when you assign an int to a char in C? Does it always just ignore the extra bits on the left?

例(4字节INT):

unsigned char c = 0;
unsigned int i = 500;

c = i; // c is 244

c = i << 24 >> 24; //c is 244

i = i << 24 >> 24; //i is 244

在二进制文件, 500 111110100 244 11110100

In binary, 500 is 111110100 and 244 is 11110100.

推荐答案

通常情况下,这正是发生了什么。在ISO / IEC 9899的第6.3.1.3节:2011标准prescribes什么在这种情况下发生的:

Typically, this is exactly what happens. Section 6.3.1.3 of the ISO/IEC 9899:2011 standard prescribes what has to happen in this case:

6.3.1.3符号和无符号整数


  1. 当与整数类型的值被转换为另一个整数
    键入比_Bool其它,如果该值可再被新psented $ P $
    类型,这是不变的。

  2. 否则,如果新类型是无符号,值被转换
    反复加上或减去小于最大值多一个
    这可以在新型psented重新$ P $直到该值在
    范围的新类型。 60)

  3. 否则,新的类型是有符号和值不能
    再在它psented $ P $;任一结果是实现定义或
    实现定义的信号提高。

60)规则描述了对数学的价值,一个给定类型的前pression的不是值的算术。

60) The rules describe arithmetic on the mathematical value, not the value of a given type of expression.

您上述的情况下2项瀑布下(因为你的性格被宣告为无符号)。在典型的计算机运算,其结果将是完全按照所描述

Your case falls under item 2 above (since your character is declared as unsigned). In a typical computer arithmetic, the result will be exactly as you described.

这篇关于如何从int分配到char在C工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆