signed char shifting issue

What the result of code below:

char ch = 0x80;

printf("char after shift: ch >> 2 = %d\n", ch>>2);

I thought it maybe 32 cause I didn't notice there is a big difference between signed and unsigned char while shifting.

The right answer is -32. Here is the reason:

Char will be converted into an int while bit-shifting. So when it's a negative number, the higher three bytes will be filled up with 1. Those 1 are pulled in while shifting right. So 0x80 becomes 0xe0, and it's -32.

But refer to C89, the conclusion above is not absolutely right. It's implementation-defined.

 Quote Originally Posted by C89

The result of E1 >> E2 is E1 right-shifted E2 bit positions. 
If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, 
the value of the result is the integral part of the quotient of E1 divided by the quantity, 
2 raised to the power E2. If E1 has a signed type and a negative value, 
the resulting value is implementation-defined.

So remember to use unsigned char if you want to do a right shift.




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值