在一个块中交换最后两个半字节

时间:2016-02-19 23:24:15

标签: python binary

我正在尝试交换decNum块中的最后两个半字节。我知道如何在这段代码中实现它:

list = [132, 201, 141, 74, 140, 94, 141, 140, 141, 15, 31, 164, 90, 229, 201, 141, 78, 114, 241, 217, 141, 217, 140, 180, 141, 164, 51, 141, 188, 221, 31, 164, 241, 177, 141, 140, 51, 217, 141, 201, 229, 152, 141, 78, 241, 114, 78, 102, 94, 141, 74, 152, 31, 152, 141, 94, 201, 31, 164, 102, 164, 51, 90, 141, 201, 229, 164, 31, 201, 152, 152, 51, 115]
key = 84
decrypted = []
for number in list:
    decNum = number | key
    bytes = bin(decNum)
    print(decNum," Bin:",bytes)

例如,如果它被赋予数字6(00000110),它应该交换最后两个半字节,因此输出应为9(00001001)

1 个答案:

答案 0 :(得分:2)

def swap_nibbles(byte:int) -> int:
    if byte >= 256: raise ValueError("Byte values must be 0..255")

    low_nibble = byte & 0x0F
    high_nibble = byte & 0xF0
    result = (high_nibble >> 4) | (low_nibble << 4)
    return result

你必须弄清楚在哪里调用它,从你的问题中不清楚你想要做什么。