问题
How can I get the x LSBs from a string (str) in Python? In the specific I have a 256 bits string consisting in 32 chars each occupying 1 byte, from wich i have to get a "char" string with the 50 Least Significant Bits.
回答1:
So here are the ingredients for an approach that works using strings (simple but not the most efficient variant):
ord(x)yields the number (i.e. essentially the bits) for a char (e.g.ord('A')=65). Note thatordexpects really an byte-long character (no special signs such as € or similar...)bin(x)[2:]creates a string representing the numberxin binary.
Thus, we can do (mystr holds your string):
l = [bin(ord(x))[2:] for x in mystr] # retrieve every character as binary number
bits = ""
for x in l: # concatenate all bits
bits = bits + l
bits[-50:] # retrieve the last 50 bits
Note that this approach is surely not the most efficient one due to the heavy string operations that could be replaced by plain integer operations (using bit-shifts and such). However, it is the simplest variant that came to my mind.
回答2:
I think that a possible answer could be in this function:
mystr holds my string
def get_lsbs_str(mystr):
chrlist = list(mystr)
result1 = [chr(ord(chrlist[-7])&(3))]
result2 = chrlist[-6:]
return "".join(result1 + result2)
this function take 2 LSBs of the -7rd char of mystr (these are the 2 MSBs of the 50 LSBs)
then take the last 6 characters of mystr (these are the 48 LSB of the 50 LSB)
Please make me know if I am in error.
回答3:
If it's only to display, wouldn't it help you?
yourString [14:63]
You can also use
yourString [-50:]
For more information, see here
来源:https://stackoverflow.com/questions/9903053/get-the-x-least-significant-bits-from-a-string-in-python