对char进行按位运算可得出32位结果 [英] Bitwise operation on char gives 32 bit result

查看:51
本文介绍了对char进行按位运算可得出32位结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在用C编写程序,将char的前4位移到末尾,将后4位移到开始.对于大多数值,它可以正常工作,也可以进行反向操作,但是对于某些值,例如8,x,y,z,它给出的结果是32位值.通过打印变量的十六进制值检查的值.谁能解释为什么会这样?

I've been writing a program in C to move the first 4 bits of a char to the end and the last 4 to the start. For most values it works normally, as well as the reverse operation, but for some values, as 8, x, y, z, it gives as result a 32 bit value. Values checked through printing hex value of the variable. Can anybody explain why this is happening?

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char o, f,a=15;
    scanf("%c",&o);
    printf("o= %d\n",o);
    f=o&a;
    o=o>>4;
    printf("o= %d",o);
    o=o|(f<<4);
    printf("o= %x, size=%d\n",o,sizeof(o));
    f=o&a;
    o=o>>4;
    printf("o= %d",o);
    o=o|(f<<4);
    printf("o= %x, size=%d\n",o,sizeof(o));
    return 0;
}

推荐答案

o 作为参数传递给 printf()会导致自动转换为 int,它在您的系统上显然是32位的.自动转换使用符号扩展名,因此,如果将 o 中的位7置1,则将转换结果中的位8-31置1,这将解释您所看到的内容.

Passing o as an argument to printf() results in an automatic conversion to int, which is apparently 32-bit on your system. The automatic conversion uses sign-extension, so if bit 7 in o is set, bits 8-31 in the converted result will be set, which will explain what you are seeing.

您可以使用 unsigned char 而不是 char 来避免这种情况.或通过 o&0xff printf().

You could use unsigned char instead of char to avoid this. Or pass o & 0xff to printf().

这篇关于对char进行按位运算可得出32位结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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