Reading binary data in human readable format

Hi, I'm new to C++ and I'm trying to read various amounts of binary data from a file. I'm reading the first blockchain from BitCoin as an example. I need to read the first 4 bytes and output the answer "D9B4BEF9" to the screen. I can get an array in reverse order and show it on the screen.

Once I have that right I want to read the next 4 bytes, 80 bytes, etc. I'm using standard C++ simple programming so I can get an understanding of the code etc. I'm not using any OOP at the moment. There are examples on how to read blockchain data but I'm lost with it.

What I need is to format the output, and then to read the next set of data. That is all for now!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <fstream>

using namespace std;

char * buffer;

int main() {

  streampos pos;
  ifstream infile;

  infile.open("blk00000.dat", ios::binary | ios::in);

  // Read magic number
  buffer = new char[4];
  infile.read(buffer, 4);

  // append the null byte to terminate the string
  buffer[4] = '\0';

  // loop over the 4 bytes read, and print
  for(int i = 0; i < 4; i++) {
    printf("Buffer[%d] is %X\n", i, buffer[i]);
  }

  delete[] buffer;
  infile.close();

}
Line 20: This is an out of bounds reference. You only allocated 4 bytes (0-3). This null terminator is not needed anyway since you're printing the characters as hex values and not printing them as a C-string.

Other than that, your code looks likie it should be fine.
Thanks for the answer. Yes, that code works, but it is returning the values byte by byte. I just want a string out with the 4 bytes in the right order (answer must be: d9b4bef9) This value needs to be in a variable and not just printed out in a nice format.

Secondly, I want to read the next 4 bytes, get that value and then the next 80, etc...
Have you seen?

Disch's tutorial to good binary files
http://www.cplusplus.com/articles/DzywvCM9/

Andy

Hi Andy

Thanks for the lead. I'll look into it in more detail. Doesn't make sense at the moment.

I just want to get a variable out with the correct data.

Registered users can post here. Sign in or register to post.