Better HN
topnewbestaskshowjobs
Log inSign up

stillwrong

1 karma · joined Jan 19, 2022 (4y ago) · 1 submissions

Submissions

comment 4y ago · link · parent

The function doesn't do the comment says it does. The code to "Swap the bits." just turns the bits on.

    >>> 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'