左移运算符(<<),右移运算符(>>)

发布时间:2023年12月19日
#include <stdio.h>








int main() 
{
    int a = 10, b = 10, c = -10, d = -10;
    int a1 = 0, a2 = 0, a3 = 0, a4 = 0, a5 = 0; 
    int b1 = 0, b2 = 0, b3 = 0, b4 = 0, b5 = 0; 
    int c1 = 0, c2 = 0, c3 = 0, c4 = 0, c5 = 0; 
    int d1 = 0, d2 = 0, d3 = 0, d4 = 0, d5 = 0;
    //a=10,左移
    a1 = a << 1;  
    a2 = a << 2;
    a3 = a << 3;
    a4 = a << 4;
    a5 = a << 5;
    //b=10,右移
    b1 = b >> 1;
    b2 = b >> 2;
    b3 = b >> 3;
    b4 = b >> 4;
    b5 = b >> 5;
    //c=-10,左移
    c1 = c << 1;
    c2 = c << 2;
    c3 = c << 3;
    c4 = c << 4;
    c5 = c << 5;
    //d=-10,右移
    d1 = d >> 1;
    d2 = d >> 2;
    d3 = d >> 3;
    d4 = d >> 4;
    d5 = d >> 5;

    printf(" a=%d  ,b=%d , c=%d , d=%d \n", a, b, c, d);
    printf("a1=%d  ,b1=%d ,c1=%d , d1=%d \n", a1, b1, c1, d1);
    printf("a2=%d  ,b2=%d ,c2=%d , d2=%d \n", a2, b2, c2, d2);
    printf("a3=%d  ,b3=%d ,c3=%d , d3=%d \n", a3, b3, c3, d3);
    printf("a4=%d ,b4=%d ,c4=%d, d4=%d \n", a4, b4, c4, d4);
    printf("a5=%d ,b5=%d ,c5=%d, d5=%d \n", a5, b5, c5, d5);

    return 0;
}

对于非负数,在不溢出前提下:

a左移k位:等效于数据*2^k,即乘以2^k;

b右移k位:等效于数据/2^k,即除以2^k;

当移动数据为负数时,符号位位置不变

对于负数,在不溢出前提下:

左移k位:等效于数据*2^k,即乘以2^k;

右移k为:等效于数据/2^k且向下取整; (向下取整:-5>>2=-3,向零取整:-5/2=-2)

attention:左移和右移均可能出现溢出,等会续上..

左移溢出很好理解,即数据超出了变量所能表示的范围;

文章来源:https://blog.csdn.net/weixin_46855342/article/details/135080694
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。