0

I have a sequence of bits for example 0101, and I want to save this sequence to a file in binary format and while opening the saved file using a binary viewer, I need to show me exactly 0101 [I mean 4 bits]. but it showed me 00000000 00000001 00000000 00000001 [and this is 32 bits]. May I ask you to help me guys? Thanks

My Code:

f = open('my_file', 'w+b')
byte_arr = [0, 1, 0, 1]
binary_format = bytearray(byte_arr)
print(binary_format)
f.write(binary_format)
f.close()

The Screenshot:

binary file

Aaron
  • 37
  • 6
  • 1
    Binary viewers are always going to show groups of 8 bits, that's just the way they work. – Mark Ransom Jul 29 '21 at 17:47
  • @MarkRansom Thank for you reply. You mean I can not save 0101 in a file? – Aaron Jul 29 '21 at 17:49
  • 1
    There is no way to write only 4 bits to a file. If you try, you'll get 8 bits anyway. – Mark Ransom Jul 29 '21 at 17:51
  • 1
    You might find the answers to [How to read bits from a file?](https://stackoverflow.com/questions/10689748/how-to-read-bits-from-a-file) useful (esp [my own](https://stackoverflow.com/a/10691412/355230) which also features a `BitWriter` class). – martineau Jul 29 '21 at 18:30

1 Answers1

0

If you want to bit sequence 0101 then you can define that using a binary literal

>>> 0b0101
5  # in decimal

If you are starting from an array of bits, then you can use int with base 2

>>> byte_arr = [0, 1, 0, 1]
>>> int(''.join(str(i) for i in byte_arr), 2)
5
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • Thanks for you reply. I'm working on a compression algorithm (Huffman Coding) and I want to save 0101 in a file and while right clicking on the file and go to properties, it shows me the size of 4 bits. Is it possible? – Aaron Jul 29 '21 at 17:52
  • 1
    You cannot have a file size of only 4 bits for [various reasons](https://stackoverflow.com/questions/26002504/whats-the-smallest-possible-file-size-on-disk). – Cory Kramer Jul 29 '21 at 17:58