How to convert huge binary data into ASCII format?
<p>I want to read a file which contains huge binary data. I want to convert this binary data into ASCII format. At the time of start, I want to read 2 bytes which indicates size of message, message is ahead of size. After reading this whole message, again repeat same action, 2 bytes for size of message and then actual message.</p>

<p><strong>code to print input data-</strong></p>

<pre><code>with open("abc.dat", "rb") as f:
byte = f.read(1)
i = 0 
while byte:
    i += 1
    print byte+' ',
    byte = f.read(1)
    if i is 80:
        sys.exit()
</code></pre>

<p><strong>Input Data(80 bytes)-</strong> </p>

<pre><code>  O  T  C  _  A  _  R  C  V  R                                                            P  V  ï¿½  W          ï¿½  w              /  ï¿½              ï¿½  ï¿½  '            ï¿½  ï¿½  &amp;  ï¿½  
</code></pre>

<p>edit1-
                                  .    >
<strong>output ussing hexdump -n200 otc_a_primary_1003_0600.dat command-</strong></p>

<pre><code>0000000 4f03 4354 415f 525f 5643 0052 0000 0000
0000010 0000 0000 0000 0000 0000 0000 0000 0000
0000020 0000 0000 0000 0000 5650 57f2 0000 0000
0000030 77d1 0002 0000 0000 902f 0004 0000 0000
0000040 a2bd 1027 0000 0000 d695 e826 2e0b 3e11
0000050 aa55 0300 f332 0000 0046 0000 0000 0000
0000060 5650 57f2 0000 0000 22f8 0a6c 0000 0000
0000070 3030 3030 3730 3435 5135 0000 0000 0100
0000080 bdb4 0100 3000 5131 5a45 1420 077a 9c11
0000090 3591 1416 077a 9c11 dc8d 00c0 0000 0000
00000a0 0000 4300 5241 2020 7f0c 0700 ed0d 0700
00000b0 2052 2020 2030 aa55 0300 f332 0000 0046
00000c0 0000 0000 0000 5650                    
00000c8
</code></pre>

<p>I'm using python's <a href="https://docs.python.org/2/library/struct.html" rel="nofollow">struct</a> module. python version - python 2.7.6</p>

<p><strong>program code-</strong></p>

<pre><code>import struct

msg_len = struct.unpack('h', f.read(2))[0]
msg_data = struct.unpack_from('s', f.read(msg_len))[0]
print msg_data
</code></pre>

<p>But I'm not able to see actual message, only single character is printing on console. How I can read such binary file's message in appropriate manner?</p>

<p>Try:</p>

<pre><code>import struct

with open('abc.dat', 'rb') as f:
    while True:
        try:
            msg_len = struct.unpack('h', f.read(2))[0] # assume native byte order
            msg_data = f.read(msg_len) # just read 'msg_len' bytes
            print repr(msg_data)
        except:
            # something wrong or reach EOF
            break
</code></pre>

python struct python-2.x binascii