[Python] How to properly transform a string with bitwise operations

Discussão em 'Python' iniciado por Stack, Fevereiro 28, 2025.

  1. Stack

    Stack Membro Participativo

    I need to convert the string "100" using bitwise without if after two adjacent digits The relation 100 is divided:

    • taking the first 1 and the second 0, we get the string 10
    • taking the first 0 and the second 0, we get 11

    Accordingly, the condition is that instead of two digits, we must put 1 or 0 (opposite bit2). My python code does not work correctly when 00 is taken.

    Maybe someone can advise how to fix it properly?

    code

    def _str_to_bytes(virkne) -> bytes:
    bin_data = virkne.zfill((len(virkne) + 7) // 8 * 8)
    data_in_bytes = int(bin_data, 2).to_bytes((len(bin_data) + 7) // 8, byteorder='big')
    return data_in_bytes

    virkne = "100"
    garums = len(virkne)

    byte = _str_to_bytes(virkne)
    int_value = int.from_bytes(byte, byteorder='big')

    print(f"virkne is: {int_value:02b}")

    for i in range(garums - 1):
    print('-'*30)
    bit1 = (int_value >> (garums - 1 - i)) & 1
    bit2 = (int_value >> (garums - 2 - i)) & 1
    ad = (bit1 << 1) | bit2
    print(f"{bit1}{bit2} -> 0b{ad:02b} = {ad}")

    modified = (int_value & ~(0b10 << (garums - 2 - i))) | ((1 - bit2) << (garums - 2 - i))
    print(f"Modified: {modified} ({modified:0{garums-1}b})")


    output:

    virkne is: 100
    ------------------------------
    10 -> 0b10 = 2
    Modified: 2 (10)
    ------------------------------
    00 -> 0b00 = 0
    Modified: 5 (101)

    Continue reading...

Compartilhe esta Página