# 位运算之左移右移运算之详解

#include "stdio.h"char leftshift(char i, int n){    if(n < 0)        return -1;    return i<<n;}char rightshift(char i, int n){    if(n < 0)        return -1;    return i>>n;}int main(){    //leftshift    char a1 = 127;    char a2 = -1;    for(int i = 1; i <= 8; i++)        printf("%d<<%d = %d;\n", a1, i, leftshift(a1,i));    for(i = 1; i <= 8; i++)        printf("%d<<%d = %d;\n", a2, i, leftshift(a2,i));    //rightshift    a1 = 127;    a2 = -128;    for(i = 1; i <= 8; i++)        printf("%d>>%d = %d;\n", a1, i, rightshift(a1,i));    for(i = 1; i <= 8; i++)        printf("%d>>%d = %d;\n", a2, i, rightshift(a2,i));    return 0;}

127<<1 = -2;127<<2 = -4;127<<3 = -8;127<<4 = -16;127<<5 = -32;127<<6 = -64;127<<7 = -128;127<<8 = 0;-1<<1 = -2;-1<<2 = -4;-1<<3 = -8;-1<<4 = -16;-1<<5 = -32;-1<<6 = -64;-1<<7 = -128;-1<<8 = 0;127>>1 = 63;127>>2 = 31;127>>3 = 15;127>>4 = 7;127>>5 = 3;127>>6 = 1;127>>7 = 0;127>>8 = 0;-128>>1 = -64;-128>>2 = -32;-128>>3 = -16;-128>>4 = -8;-128>>5 = -4;-128>>6 = -2;-128>>7 = -1;-128>>8 = -1;

1、127的补码：0111 1111

2、-128的补码：1000 0000

1、与0相与可清零
2、与1相与可保留原值

1、与0相或可保留原值
2、与1相与可齐设1

1、与0异或保留原值
2、与1异或比特值反转
3、可通过某种算法，使用异或实现交换两个值

posted @ 2011-01-14 15:46  子扬  阅读(60533)  评论(0编辑  收藏  举报