# 移位

Home / 移位

### 移位

2015-2-10 23:33:06 | Linux C | 没有评论

2年前被Boss问了个问题，好像就是变量的倍数如何写，迟疑地问：不是直接乘么？然后结果可想而知，当然当时想要我回答的答案是移位，时过境迁，突然在想，如今这么潮的编译器难道不会优化成移位么

```x               0110 0011               x               1001 0101
x << 4          0011 0000               x << 4          0101 0000
x >> 4(逻辑)    0000 0110               x >> 4(逻辑)    0000 1001
x >> 4(算术)    0000 0110               x >> 4(算术)    1111 1001```

```#include <stdio.h>

void main(){
int a = 0xFEAB98CD << 32;
int b = 0xFEAB98CD >> 32;
unsigned c = 0xFEAB98CDu >> 32;
printf("a=%x\n", a);
printf("b=%x\n", b);
printf("c=%x\n", c);
}

[lihui@localhost ~]# cc lihui.c
lihui.c:4: warning: left shift count >= width of type
lihui.c:5: warning: right shift count >= width of type
lihui.c:6: warning: right shift count >= width of type

[lihui@localhost ~]# ./a.out
a=0
b=0
c=0```

```#include <stdio.h>

void main(){
int a = 0xFEAB98CD << 28;
int b = 0xFEAB98CD >> 30;
unsigned c = 0xFEAB98CDu >> 28;
printf("a=%x\n", a);
printf("b=%x\n", b);
printf("c=%x\n", c);
}
[lihui@localhost ~]# cc lihui.c
[lihui@localhost ~]# ./a.out
a=d0000000
b=3
c=f```