In [3]:
import hexdump
In [6]:
hexdump.hexdump('\x00'*16)
In [ ]:
In [7]:
# CORRECT CODE FOR WRITE BITS
from array import *
bin_array = array('B')
bin_array.append(int('011',2))
bin_array.append(int('010',2))
bin_array.append(int('110',2))
f = file('binary.mydata','wb')
bin_array.tofile(f)
f.close()
#output: xxd -b binary.mydata
#00000000: 00000011 00000010 00000110
In [8]:
# correct code
from cStringIO import StringIO
s = "001011010110000010010"
sio = StringIO(s)
f = open('outfile', 'wb')
while 1:
# Grab the next 8 bits
b = sio.read(8)
# Bail if we hit EOF
if not b:
break
# If we got fewer than 8 bits, pad with zeroes on the right
if len(b) < 8:
b = b + '0' * (8 - len(b))
# Convert to int
i = int(b, 2)
# Convert to char
c = chr(i)
# Write
f.write(c)
f.close()
# output $ xxd -b outfile
# 00000000: 00101101 01100000 10010000
In [15]:
# CORRECT CODE FOR WRITE BITS IN BUNCH OF 8 ONLY, MORE THAN THAT IT GIVES ERROR "OverflowError: unsigned byte integer is greater than maximum"
from array import *
bin_array = array('B')
bin_array.append(int('010110',2))
#bin_array.append(int('01010101010101010101010101010101010101010101010',2))
bin_array.append(int('11110000',2))
f = file('binary.mydata1','wb')
bin_array.tofile(f)
f.close()
In [19]:
# correct code
from cStringIO import StringIO
#s = "010101010101010101010101010101010101010101010101"
s = "11111111111111111111111111111111111111111111111111"
sio = StringIO(s)
f = open('outfile1', 'wb')
while 1:
# Grab the next 8 bits
b = sio.read(8)
# Bail if we hit EOF
if not b:
break
# If we got fewer than 8 bits, pad with zeroes on the right
if len(b) < 8:
b = b + '0' * (8 - len(b))
# Convert to int
i = int(b, 2)
# Convert to char
c = chr(i)
# Write
f.write(c)
f.close()
# output $ xxd -b outfile
# 00000000: 00101101 01100000 10010000
In [ ]: