First of all, you will not get a file size that is not a multiple of 8 bits on any popular platform.
Second, you really have to brush up an what "binary" actually means. You confuse two different concepts: representing a number in the binary number system and writing out data in a "non human readable" form.
Actually, you are confusing two even more fundamental concepts: data and the representation of data. "12ab"
is a representation of the four bytes in memory, as is "\x31\x32\x61\x62"
.
Your problem is that x
contains 28 bytes of data that can either be represented as "0110001011001011000011100010"
or as "\x30\x31\x31\x30\x30...\x30\x30\x31\x30"
.
Maybe this will help you:
>>> hexstr = "12ab"
>>> len(hexstr)
4
>>> ['"%s": %x' % (c, ord(c)) for c in hexstr]
['"1": 31', '"2": 32', '"a": 61', '"b": 62']
>>> i = 42
>>> hex(i)
'0x2a'
>>> x = '{0:07b}'.format(i)
>>> x
'0101010'
>>> [hex(ord(c)) for c in x]
['0x30', '0x31', '0x30', '0x31', '0x30', '0x31', '0x30']
>>> hex(ord('0')), hex(ord('1'))
('0x30', '0x31')
>>> import binascii
>>> [hex(ord(c)) for c in binascii.unhexlify(hexstr)]
['0x12', '0xab']
That said, thhe binascii module has a method you can use:
import binascii
data = binascii.unhexlify(hexstr)
with open('outputfile.bin', 'wb') as f:
f.write(data)
This will encode your data in 8bit instead of 7bit, but usually it is not worth the effort to use 7bit for compression reasons anyway.