Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
From list of bits to PDF
#1
Hello!
I am working on a simple program that works for PDF files. So far I’ve been able to read the PDF into a list of bytes with the following code:
    def bstr(n): # n in range 0-255
        return ''.join([str(n >> x & 1) for x in (7,6,5,4,3,2,1,0)])
    def read_binary():
        f = open('source.pdf','rb')
        binlist = [ ]
        while True:
            bin = struct.unpack('B',f.read(1))[0] 
            if not bin:
                break
            strBin = bstr(bin)
            binlist.append(strBin)
        return binlist
After performing some math operations on the list of bit sequences, I would like to get back the PDF file. Is there any way I can reconstruct the PDF file starting from the list of bit sequences?
Reply
#2
I would rather do it this way
>>> import io
>>> f = io.BytesIO(b'foo bar baz')
>>> L = [bin(c)[2:] for c in f.read()]
>>> L
['1100110', '1101111', '1101111', '100000', '1100010', '1100001', '1110010', '100000', '1100010', '1100001', '1111010']
>>> b = bytes([int(s, 2) for s in L])
>>> b
b'foo bar baz'
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Is it possible to extract 1 or 2 bits of data from MS project files? cubangt 8 1,070 Feb-16-2024, 12:02 AM
Last Post: deanhystad
  How to rotate bits ? korenron 2 1,638 Mar-23-2022, 04:05 PM
Last Post: Larz60+
Exclamation Help in breaking bytes into bits through masking and shifting kamui123 9 4,590 Jan-11-2021, 07:42 AM
Last Post: kamui123
  rounding floats to a number of bits Skaperen 2 2,322 Sep-13-2019, 04:37 AM
Last Post: Skaperen
  Problem with Pycharm 64 bits sylas 12 10,265 Jan-22-2018, 02:19 PM
Last Post: sparkz_alot
  send bits to the signal generator liorjo 2 3,120 Dec-20-2017, 07:46 PM
Last Post: liorjo
  How to convert python files from 32 bits tto 64 bits sylas 2 5,094 Oct-29-2017, 03:51 AM
Last Post: Larz60+
  Why are two similar bits of code giving different results? godmode 10 9,973 Dec-15-2016, 09:53 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020