擅长:python、mysql、java
<p>下面是一种针对文本示例的方法—Python不会像Java/C那样将字符转换为int。相反,您将获得序数值,然后将其转换为二进制数</p>
<pre><code>def to_bin(c):
bin_rep = bin(ord(c))
print bin_rep # for testing
return bin_rep # can be written to a file here or not...
text = "Hello there"
for each_char in text:
to_bin(each_char)
</code></pre>
<p>我认为这种方法值得用一个输入文件的示例来尝试,然后重构为一个文件r/w</p>
<p>要对文件执行此操作,请尝试以下操作:</p>
<pre><code>write_str = ""
with open('program.txt', 'r') as plik: # otwieramy plik do odczytu
for line in plik:
for each_char in line:
write_str += str(to_bin(each_char))
with open('wyniki.txt', 'w') as plik1:
plik1.write(write_str)
plik1.close()
plik.close()
</code></pre>
<p>如果要反转字节的顺序,可以反转或更改整个文件
写入\u str+=str(到\u bin(每个\u字符))
到
write_str=str(到\u bin(每个字符))+write_str</p>