簡體   English   中英

大整數上的位操作左移 Python

[英]Bit operation Left Shift Python on big integers

我正在嘗試使用大整數在 python 上實現左位移。 由於它們的大小,我想將它們的位值存儲在文件中並在之后處理文件,就位字符串而言它對於我的 RAM 來說太大了。 但是,我在不使用二進制表示的情況下刪除 int 的前 N ​​位時遇到問題,但我不能。 這是我到目前為止所做的:

def __lshift(self, n, d):
    N = n.bit_length()
    if N > 2**20: # n is big and we have to use files
        temp = open('bin.tmp','w')
        while N > 2**20:
            n_ = n >> 20 # Take the 20 first bits of n
            temp.write(bin(n)[2:])
            # Here I would like to delete 20 first bits of n
    else:
        bin_ = bin(n)[2:]
        bin_ = bin_[:N-d] + bin_[d:]
        return int(bin_,2)

謝謝你的幫助 !

這是我最終找到的解決方案:

def lshift(n,d):
def one_turn(n):
    N = n.bit_length()
    end = n >> N-1
    begin = (n & ((1 + (1 << N-1) - 1) ^ ((1 << N) - 1))) << 1
    return begin + end

for i in range(d):
    n = one_turn(n)
return n

最后比我想做的更容易:)

暫無
暫無

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

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