以二进制格式显示1和0的字符串 [英] Display a string of 1's and 0's in binary format Python
本文介绍了以二进制格式显示1和0的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有什么方法可以从二进制格式中实际获取1和0的字符串?
Is there any way to actually get a string of 1's and 0's from a binary format ?
# read in image data
fh = open('test.png','rb')
data = fh.read()
fh.close()
# write binary to text file
fh = open('test.txt','w')
fh.write(data)
fh.close
fh.close()
如何将数据字符串转换为1和0
how can i turn that data string into 1's and 0's
推荐答案
这会将字符串中的每个字节转换为8个二进制数字,并用空格分隔它们.您可以轻松更改分隔符.
This will convert each byte in your string to 8 binary digits and separate them with a space. You can easily change the separator.
data = " ".join(bin(ord(b))[2:].rjust(8, "0") for b in data)
这篇关于以二进制格式显示1和0的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文