Bits Manipulation Flashcards
How to remove the lowest set bit in x?
How to extract the lowest set bit in x?
How to remove the lowest set bit in x?
x & (x - 1)
How to extract the lowest set bit in x?
x & ~(x - 1)
print(bin(4))
0b100
2 ** 2
print(bin(8))
0b1 000
2 ** 3
print(bin(16))
0b10 000
2 ** 4
print(bin(32))
0b100 000
2 ** 5
print(bin(64))
0b1000 000
2 ** 6
print(bin(128))
0b10 000 000
2 ** 7
print(bin(256))
0b100 000 000
2 ** 8
print(bin(512))
0b1 000 000 000
2 ** 9
print(bin(1024))
0b10 000 000 000
2 ** 10
2 ** 5
32
2 ** 6
64
2 ** 7
128
2 ** 8
256
2 ** 9
512
hex_num = “0xF”
decimal_num = int(hex_num, 16)
binary_num = bin(decimal_num)
print(binary_num)
What does this print out?
print(binary_num) # Output: ‘0b1111’
num = hex(0b111)
print(num)
‘0x7’
num = hex(0b11)
print(num)
‘0x3’
num = hex(0b1111)
print(num)
‘0xf’
num = hex(0b11111)
print(num)
‘0x1f’
decimal = -1
What’s the 8-bit Two’s Complement of decimal?
8-bit Two’s Complement of -1 = 1111 1111
8-bit Two’s Complement of 1 = 0000 0001
只有2的几次方的数 正数和负数的significant digit都一样 其他digit 都相反
decimal = -2
What’s the 8-bit Two’s Complement of decimal?
8-bit Two’s Complement of -2 = 1111 1110
8-bit Two’s Complement of 2 = 0000 0010
只有2的几次方的数 正数和负数的significant digit都一样 其他digit 都相反
decimal = -4
What’s the 8-bit Two’s Complement of decimal?
8-bit Two’s Complement of -4 = 1111 1100
8-bit Two’s Complement of 4 = 0000 0100
只有2的几次方的数 正数和负数的significant digit都一样 其他digit 都相反
decimal = -128
What’s the 8-bit Two’s Complement of decimal?
8-bit Two’s Complement of -128 = 1000 0000
8-bit Two’s Complement of 128= 1000 0000
只有2的几次方的数 正数和负数的significant digit都一样 其他digit 都相反
current_bit &1
current_bit &0
current_bit ^ 1
current_bit ^ 0
What do these do to the current bit?
current_bit &1 = current bit stays the same
current_bit &0 = current bit gets erased
current_bit ^ 1 = flips the current bit
current_bit ^ 0 = current bit stays the same
What happens with XOR?
a ^ b = c
a, b are binary bits
c = 0 when a == b
c = 1 when a != b
With 2’s complement, -x = ________ ?
-x = ~x + 1
~x = -x - 1
With 2’s complement, ~x is ?
~x = -x -1
We have an integer x,
how can we convert it to -x using binary operations?
- subtract 1 from x
- flip each bit of 1
x = 0001
x - 1 = 0000
flipped x - 1 =1111 = -1