简体   繁体   中英

Bit operation Left Shift Python on big integers

I am trying to implement a left bit shift on python with big integers. Because of their size, I want to stock their bit value on a file and work on the file after, as far as the bit string it too big for my RAM. However, I am facing problem deleting the N first bits of the int without using its binary representation, as far as I can't. Here is what I did so far:

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)

Thanks for your help !

Here is the solution I finally found :

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

Finally easier than what I was trying to do :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM