如何移位运算符用C评估? [英] How is shift operator evaluated in C?
问题描述
最近,我注意到一个(怪异)的行为,当我进行使用移位操作>>
<<
!
要解释它,让我写这个小的可运行code,做它应该是相同的(在我的理解)两次手术,但我有不同的结果感到惊讶!
的#include<&stdio.h中GT;诠释主要(无效){
unsigned char型A = 0×05,B = 0×05; //第一次手术
一个=((A&所述; 7;)>大于7); //第二次手术
B<< = 7;
B>> = 7; 输出(A =%X B =%X \\ n,A,B);
返回0;
}
在跑, A = 5
和 B = 1
。我希望他们都等于1!可有人好心解释为什么我得到了这样的结果?
P.S:在我的环境 unsigned char型
的大小为1字节
移位操作会做整型的提升,其操作数,并在code产生的 INT
转换回字符
是这样的:
//第一次手术
一个=((A&所述; 7;)>大于7); // A =(char)的((A<< 7)>> 7);//第二次手术
B<< = 7; // B =(char)的(B<< 7);
B>> = 7; // B =(char)的(B>> 7);
从N1570草案(成为C11的标准更高版本)报价:
6.5.7按位移位运算符:
<醇开始=2>
每个操作数应具有整数类型。
整数促销活动在每个操作数执行。该结果的类型是,促进左操作数。如果右操作数的值是负的或大于或等于促进左操作数的宽度,其行为是不确定的。
块引用>和它应该在C99和C90也有类似的声明。
I recently noticed a (weird) behavior when I conducted operations using shift
>>
<<
!To explain it, let me write this small runnable code that does two operations which are supposed to be identical(In my understanding), but I'm surprised with different results!
#include <stdio.h> int main(void) { unsigned char a=0x05, b=0x05; // first operation a = ((a<<7)>>7); // second operation b <<= 7; b >>= 7; printf("a=%X b=%X\n", a, b); return 0; }
When ran,
a = 5
andb = 1
. I expect them both to be equal to 1! Can someone kindly explain why I got such a result?P.S: In my environment the size of
unsigned char
is 1 byte解决方案The shift operations would do integer promotions to its operands, and in your code the resulting
int
is converted back tochar
like this:// first operation a = ((a<<7)>>7); // a = (char)((a<<7)>>7); // second operation b <<= 7; // b = (char) (b << 7); b >>= 7; // b = (char) (b >> 7);
Quote from the N1570 draft (which became the standard of C11 later):
6.5.7 Bitwise shift operators:
- Each of the operands shall have integer type.
- The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.
And it's supposed that in C99 and C90 there are similar statements.
这篇关于如何移位运算符用C评估?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!