簡體   English   中英

僅使用位運算符實現轉碼

[英]Implementation of transcoding using only bitwise operators

我有 function 對輸入的十六進制數進行轉碼。 例如,我有這樣的數字初始格式

初始格式

function 將其轉碼為以下格式:

最終格式

我將使用內置的十六進制 function 將 function 的結果作為字符串返回。 我嘗試過這樣的事情,但沒有奏效:

def task22(number) -> str:
    """
    Returns transcoded hexadecimal string, this function uses bitwise operators to transcode given value
    :param number: hexadecimal number to transcode
    :return: Transcoded hexadecimal string
    """
    a = number & 0b111111111111111
    b = number & 0b111111111111111
    c = number & 0b11
    a = a << 17
    b = b >> 13
    c = c >> 30

    return hex(a | b | c)

如何使用按位運算符對數字進行轉碼? 我需要向左和向右使用按位移位,但我不知道如何為上述格式執行此操作。

解決了。 問題是我需要使用 32 個零(因為所有位的數量為 32)替換為 1 的按位 AND 運算符處理所有段,其中每個段位於這樣的位序列中:

def task22(number) -> str:
    """
    Returns transcoded hexadecimal string, this function uses bitwise operators to transcode given value
    :param number: hexadecimal number to transcode
    :return: Transcoded hexadecimal string
    """
    a = number & 0b00000000000000000111111111111111
    b = number & 0b00111111111111111000000000000000
    c = number & 0b11000000000000000000000000000000
    a = a << 17
    b = b >> 13
    c = c >> 30

    return hex(a | b | c)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM