开发者

Reading a signed char as unsigned - Type Promotion

Consider this little program:

#include <stdio.h>
int main()
{
    char c = 0xFF;
    printf("%d\n", c);

    return 0;
}

Its 开发者_C百科output is -1, as expected (considering char is signed in my system). What I'm trying to do is to make it print 255. This is of course a simplification of the real situation, where I can't just define c as unsigned.

The first possible change would be using %u as formatter instead, but the usual type promotion rules apply here, and the number is printed as 232 - 1.

So is there any way to read the signed char as unsigned before it gets promoted to an int? I could create a pointer to a unsigned char set to the address of c, and dereference it later, but not sure if this is the best approach.


c is being promoted using signed promotion rules. Cast c to unsigned to use unsigned promotion.

printf("%u\n", (unsigned char)c);

Unsigned char will be promoted to unsigned int.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜