alternative reading binary in python instead of C++
<p>I have a binary file and C++ code which can read that binary file like follow.</p>

<pre><code>int NumberOfWord;
FILE *f = fopen("../data/vec.bin", "rb");
fscanf(f, "%d", &amp;NumberOfWord);
cout &lt;&lt; NumberOfWord&lt; &lt;endl;
</code></pre>

<p>This output is:</p>

<pre><code>114042
</code></pre>

<p>I want to reimplement like above code in python.</p>

<pre><code>with open("../data/vec.bin","rb") as f:
    b = f.read(8)
    print struct.unpack("d",b)[0]
</code></pre>

<p>but this code is not working.
my output is:</p>

<pre><code>8.45476330511e-53
</code></pre>

<p>My question are:</p>

<p>1) why integer has 8 byte in C++.</p>

<p>I never knows %d means double.
but, actually the variable has a type of integer, but normally we output using "%d" in C++.
It is weird.</p>

<p>2) How do I extract a real number in python</p>

<p>I want to extract a real number like above C++ code in python code.
How do I that??</p>

<p>maybe, I misunderstand about struct module in python.</p>

<p>As you have been able to read the file correctly with this C++ (or rather C) line, <code>fscanf(f, "%d", &amp;NumberOfWord);</code>, I assume that your file contains a text representation of 114042. So it contains the bytes</p>

<p><code>0x31 0x31 0x34 0x30 0x34 0x32 ...</code> or <code>'1', '1', '4', '0', '4', '2', ...</code></p>

<p>When you open it in a text editor, you can see one single line <code>114042</code>.</p>

<p>Now when you try to read if as binary with <code>i</code> format, you use the 4 first bytes of the file and actually get <code>int('31313034', 16)</code>: 825308208. I could not reproduce what you get with <code>d</code> format for decoding it as double because I could not guess what comes in your file after the last digit...</p>

<p>If the number is alone on first line, it is easy: just read one line and convert it to an int:</p>

<pre><code>with open("../data/vec.bin","rb") as f:
    print int(f.readline())
</code></pre>

<p>If there are other characters after the last digit, you will have to first use a regex (do not forget to import <code>re</code>) to get the numeric value and then convert it to an int:</p>

<pre><code>with open("../data/vec.bin","rb") as f:
    line = f.readline()
    m = re.match(t'\s*\d*', line)
    print(int(m.group(0)))
</code></pre>

<p>TL/DR: Do not try to read a text file as if it contained a binary representation</p>

python c++