by asxd · 4y ago · 0 comments
# Swap the sixth bit and seventeenth bit of a 32-bit signed integer.
def swap_bits(x):
# Get the bit at position 6 and 17.
bit6 = x & (1 << 6)
bit17 = x & (1 << 17)
# Swap the bits.
x = x ^ (bit6 << 17)
x = x ^ (bit17 << 6)
return x >>> def swap_bits(x):
# Get the bit at position 6 and 17.
bit6 = x & (1 << 6)
bit17 = x & (1 << 17)
# Swap the bits.
x = x ^ (bit6 << 17)
x = x ^ (bit17 << 6)
return x
>>> x6 = (1 << 6)
>>> f"{x6:b}"
'1000000'
>>> s6 = swap_bits(x6)
>>> f"{s6:b}"
'100000000000000001000000'
Here's one that correctly swap bits. It could be made more concise. >>> def swap_specific(x,i,j):
def get(x,p): return 1 if x & (1 << p) else 0
def set(x,p): return x ^ (1 << p)
def clr(x,p): return x & ~(1 << p)
bi, bj = get(x,i), get(x,j)
x = set(x,j) if bi else clr(x,j)
x = set(x,i) if bj else clr(x,i)
return x
>>> f"{x6:b}"
'1000000'
>>> b6 = swap_specific(x6,6,17)
>>> f"{b6:b}"
'100000000000000000' def set(x,p): return x ^ (1 << p)
should probably be def set(x,p): return x | (1 << p)The Python code is wrong because the 17th bit is shifted up, not down. Also, the bits are shifted by the wrong amount, not up/down by 11 (= 17 minus 6), but up by 6 and up by 17. What a joke.
Not only that, even if the shifts were correct, it's simply xoring the bits. The swap is completely wrong.
Garbage code, total fail.