Get the x Least Significant Bits from a String in

2019-08-07 05:45发布

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.

3条回答
Deceive 欺骗
2楼-- · 2019-08-07 06:37

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 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.

查看更多
叼着烟拽天下
3楼-- · 2019-08-07 06:44

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

查看更多
神经病院院长
4楼-- · 2019-08-07 06:47

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.

查看更多
登录 后发表回答