I’m trying to read and print the binary data of a file but notice after reading the first line, with 128 bits, the subsequent lines printed out do not match the lines when I look at the binary data manually with notepad++.
JavaScript
x
41
41
1
nfp = open(new_file, 'rb')
2
dc = 0
3
ac = 0
4
short_lines = 0
5
line_string = str("")
6
for x in nfp.read():
7
if dc == 16:
8
ac += 1
9
if ac == 5:
10
break
11
else:
12
print(line_string)
13
line_string = str("")
14
dc = 0
15
continue
16
#open cmpf here and write
17
else:
18
dc += 1
19
y = str("{:08b}".format(x))
20
line_string = line_string + str(" ") + y
21
22
23
print(short_lines)
24
print("Final line count:", str(ac/128))
25
valk = input("Click any button to end program...")```
26
27
Expected output:
28
29
[enter image description here][1]
30
31
32
Actual output:
33
34
[printed data][2]
35
36
As you can see, the first line matches, but after that they are completely different. Why?
37
38
39
[1]: https://i.stack.imgur.com/pKOAA.png
40
[2]: https://i.stack.imgur.com/DBgJG.png
41
Advertisement
Answer
The problem is that when dc==16
then your program prints whole line but the current x
value is skipped (it is not used anywhere). To fix this problem you may remove else
like this:
JavaScript
1
14
14
1
for x in nfp.read():
2
if dc == 16:
3
ac += 1
4
if ac == 5:
5
break
6
else:
7
print(line_string)
8
line_string = str("")
9
dc = 0
10
11
dc += 1
12
y = str("{:08b}".format(x))
13
line_string = line_string + str(" ") + y
14