位操作对符号位的影响

先上结论

1) 右移:左侧会使用符号位补齐,比如:对于负数,右移时左侧补1;对于正数,右移时左侧补0;
2) 左移:符号位也会被左移,右侧补0
3) 取反:符号位也会被取反

测试代码

//有符号数
static void Print(int a)
{
    Console.WriteLine($"{Convert.ToString(a, 2).PadLeft(32, '0')}, {a}");

    int b = a >> 1;
    Console.WriteLine($"{Convert.ToString(b, 2).PadLeft(32, '0')} 右移, {b}"); //左侧使用符号位补齐

    int c = a << 1;
    Console.WriteLine($"{Convert.ToString(c, 2).PadLeft(32, '0')} 左移, {c}"); //符号位被左移动, 右侧补0

    int d = ~a;
    Console.WriteLine($"{Convert.ToString(d, 2).PadLeft(32, '0')} 取反, {d}"); //符号位也会被取反

    Console.WriteLine();
}

//无符号数
static void Print2(uint a)
{
    Console.WriteLine($"{Convert.ToString(a, 2).PadLeft(32, '0')}, {a}");

    uint b = a >> 1;
    Console.WriteLine($"{Convert.ToString(b, 2).PadLeft(32, '0')} 右移, {b}");

    uint c = a << 1;
    Console.WriteLine($"{Convert.ToString(c, 2).PadLeft(32, '0')} 左移, {c}");

    uint d = ~a;
    Console.WriteLine($"{Convert.ToString(d, 2).PadLeft(32, '0')} 取反, {d}");

    Console.WriteLine();
}

运行后:

static void Main(string[] args)
{
    uint a = 0x80000000;

    Print((int)a);
    Print2(a);
}

运行结果:

 

posted @ 2022-11-19 22:10  yanghui01  阅读(43)  评论(0编辑  收藏  举报