简体   繁体   中英

Get the x Least Significant Bits from a String in Python

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 which I have to get a "char" string with the 50 Least Significant Bits.

So here are the ingredients for an approach that works using strings (simple but not the most efficient variant):

  • ord(x) yields the number (ie essentially the bits) for a char (eg ord('A')=65 ). Note that ord expects really an byte-long character (no special signs such as € or similar...)
  • bin(x)[2:] creates a string representing the number x in 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.

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.

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

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