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

4
  • 1
    Binary viewers are always going to show groups of 8 bits, that's just the way they work. Commented Jul 29, 2021 at 17:47
  • @MarkRansom Thank for you reply. You mean I can not save 0101 in a file? Commented Jul 29, 2021 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. Commented Jul 29, 2021 at 17:51
  • 1
    You might find the answers to How to read bits from a file? useful (esp my own which also features a BitWriter class). Commented Jul 29, 2021 at 18:30

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

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?
You cannot have a file size of only 4 bits for various reasons.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.