简体   繁体   English

Python-将字符串转换为m位数字

[英]Python - Convert string to m-bit number

Suppose I have a string str="hello", and every char can be converted to ascii code, which is: 假设我有一个字符串str =“ hello”,并且每个字符都可以转换为ascii代码,即:

"104, 101, 108, 108, 111" = "0b01101000, 0b01100101, 0b01101100, 0b01101100, 0b01101111"

and each char is 8-bit long, each number is smaller than 2^8. 每个char为8位长,每个数字小于2 ^ 8。

Now I wonder how can I convert arbitrary m-bit long number. 现在,我想知道如何转换任意m位长数字。 For example, if m=10, then it becomes 例如,如果m = 10,则变为

"0b0110100001, 0b1001010110, 0b1100011011, 0b0001101111" = "417, 598, 795, 111"

and each number is smaller than 2^m. 并且每个数字都小于2 ^ m。

My current idea is: 我当前的想法是:

str = "hello"
tmp = ""
for i in str:
    tmp = tmp + bin(ord(i))[2:].zfill(8)

print tmp

m=10
for i in xrange(0,len(tmp),m):
    print int(tmp[i:i+m],2)

But I wonder whether there is some more efficient way to do that? 但是我想知道是否有更有效的方法来做到这一点?

Thanks! 谢谢!

If you are looking for standard conversions like binary, octal, hex; 如果您正在寻找标准转换,例如二进制,八进制,十六进制; you could use format as: 您可以使用格式为:

for binary: 对于二进制:

numbers = "417, 598, 795, 111"
print ','.join(["{0:b}".format(int(n,10)) for n in numbers.split(',')])

output: 输出:

110100001,1001010110,1100011011,1101111

You can also use int for conversion (it will not work for non valid digits): 您还可以使用int进行转换(不适用于无效数字):

print ','.join([str(int(n,16)) for n in numbers.split(',')])

output: 输出:

1047,1432,1941,273

You could do something general like this: 您可以执行以下一般操作:

s = "hello"
print ['0b{:0{bits}b}'.format(ord(c), bits=10) for c in s]

Output: 输出:

['0b0001101000', '0b0001100101', '0b0001101100', '0b0001101100', '0b0001101111']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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