截断一个int为char - 如何界定? [英] Truncating an int to char - is it defined?

查看:271
本文介绍了截断一个int为char - 如何界定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

unsigned char a, b;
b = something();
a = ~b;

一个静态分析器的最后一行抱怨截断,presumably因为 B 被晋升为int的位翻转之前,结果会是int类型。

A static analyzer complained of truncation in the last line, presumably because b is promoted to int before its bits are flipped and the result will be of type int.

我只在促进INT的最后一个字节兴趣 - 如果 B 是将0x55,我需要 A 要和0xAA。我的问题是,而作C SPEC说的截断如何发生,或者是定义/未定义实现什么?它是保证 A 总是会得到分配我所期望的价值或可以去错一个符合标准的平台上?

I am only interested in the last byte of the promoted int - if b was 0x55, I need a to be 0xAA. My question is, does the C spec say anything about how the truncation happens, or is it implementation defined/undefined? Is it guaranteed that a will always get assigned the value I expect or could it go wrong on a conforming platform?

当然,铸造结果将分配沉默静态分析过,但我想知道,如果是安全的忽略摆在首位此警告。

Of course, casting the result before assigning will silence the static analyzer, but I want to know if it is safe to ignore this warning in the first place.

推荐答案

作为的 C99标准

...如果新类型是无符号的值被重复地增加或减少超过可重新在新类型psented $ P $直到该值是新的范围内的最大值多一个转换类型。

... if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.

举例CHAR_BIT == 8的sizeof(无符号字符)== 1的sizeof(int)的== 4


Example for CHAR_BIT == 8, sizeof (unsigned char) == 1, sizeof (int) == 4

所以,将0x55转换为 INT ,为0x00000055,然后否定,0xFFFFFFAA和

So, 0x55 is converted to int, to 0x00000055, then negated to 0xFFFFFFAA, and


      0xFFFFFFAA
    + 0x00000100 /* UCHAR_MAX + 1 */
    ------------
      0xFFFFFEAA

    ... repeat lots and lots of times ...

      0x000000AA

或,作为纯和0xAA ,如你所期望

or, as plain 0xAA, as you'd expect

这篇关于截断一个int为char - 如何界定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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