In [4]:
with open('file.bin', 'wb') as f:
    f.write("1")

In [5]:
f.close


Out[5]:
<function close>

In [7]:
with open("file.bin", "rb") as binary_file:
    # Read the whole file at once
    data = binary_file.read()
    print(data)


1

In [8]:
one_byte = int('11110000', 2)
print(one_byte)


240

In [11]:
one_byte = int('000110001', 2)
print(one_byte)


49

In [24]:
a_byte = b'\x31'  # 255

In [25]:
i = ord(a_byte) # Get the integer value of the byte

In [26]:
byte1 = "{0:b}".format(i) # binary 1111111

In [27]:
print (byte1)
print (a_byte)


110001
1

In [28]:
with open('file1.bin', 'wb') as f:
    f.write(byte1)
f.close
# http://www.devdungeon.com/content/working-binary-data-python ; http://www.diveintopython3.net/serializing.html


Out[28]:
<function close>

In [29]:
with open("file.bin", "rb") as binary_file:
    # Read the whole file at once
    data = binary_file.read()
    print( data)


1

In [50]:
import struct

bits = "111100001111000011110000111100001111"  # example string. It's always 23 bits
int_value = int(bits[::-1], base=2)
print (int_value)
bin_array = struct.pack('i', int_value)
print (bin_array)
with open("test.bnr", "wb") as f:
    f.write(bin_array)


64677154575
---------------------------------------------------------------------------
error                                     Traceback (most recent call last)
<ipython-input-50-d113ca2f8d50> in <module>()
      4 int_value = int(bits[::-1], base=2)
      5 print (int_value)
----> 6 bin_array = struct.pack('i', int_value)
      7 print (bin_array)
      8 with open("test.bnr", "wb") as f:

error: 'i' format requires -2147483648 <= number <= 2147483647

In [58]:
bits = "1000000000000000000000000000000000000000000000000000000000000"
value = int(bits,2)
print (value)


1152921504606846976

In [ ]:
# read file as binary data
binFile = open(outfile,'rb')
binaryData = binFile.read(16)
hexvalue = binascii.hexlify(binaryData)
print hexvalue
# convert hex to binary value for print output file in python
binary = bin(int(hexvalue, 16))[2:]
print binary
hexa_dec = hex(int(binary, 2))[2:]
print hexa_dec