Explanation of Bitwise NOT Operator

前端 未结 7 1648
悲&欢浪女
悲&欢浪女 2020-11-30 07:00

Why is it that the bitwise NOT operator (~ in most languages) converts the following values like so:

-2 -> 1
-1 -> 0

相关标签:
7条回答
  • 2020-11-30 07:29
        Dim mask As Integer = -1
        '11111111111111111111111111111111
    
        For x As Integer = -3 To 3
            Dim i As Integer = x
            Debug.WriteLine("")
            Debug.WriteLine("'" & Convert.ToString(i, 2).PadLeft(32, "0"c) & " > Num = " & i.ToString)
    
            i = i Xor mask 'reverse the bits (same as Not)
            Debug.WriteLine("'" & Convert.ToString(i, 2).PadLeft(32, "0"c) & " > Not = " & i.ToString)
    
            i += 1 'convert to two's complement
            Debug.WriteLine("'" & Convert.ToString(i, 2).PadLeft(32, "0"c) & " > 2's Comp = " & i.ToString)
        Next
    
        'debug results
    
        '11111111111111111111111111111101 > Num = -3
        '00000000000000000000000000000010 > Not = 2
        '00000000000000000000000000000011 > 2's Comp = 3
    
        '11111111111111111111111111111110 > Num = -2
        '00000000000000000000000000000001 > Not = 1
        '00000000000000000000000000000010 > 2's Comp = 2
    
        '11111111111111111111111111111111 > Num = -1
        '00000000000000000000000000000000 > Not = 0
        '00000000000000000000000000000001 > 2's Comp = 1
    
        '00000000000000000000000000000000 > Num = 0
        '11111111111111111111111111111111 > Not = -1
        '00000000000000000000000000000000 > 2's Comp = 0
    
        '00000000000000000000000000000001 > Num = 1
        '11111111111111111111111111111110 > Not = -2
        '11111111111111111111111111111111 > 2's Comp = -1
    
        '00000000000000000000000000000010 > Num = 2
        '11111111111111111111111111111101 > Not = -3
        '11111111111111111111111111111110 > 2's Comp = -2
    
        '00000000000000000000000000000011 > Num = 3
        '11111111111111111111111111111100 > Not = -4
        '11111111111111111111111111111101 > 2's Comp = -3
    
    0 讨论(0)
提交回复
热议问题