Simon Huenecke
Simon Huenecke

Reputation: 97

Processing binary data containing different length


So I have some binary data that I read, process and need to "split" into different variables, like this:

int *buffer;
buffer = malloc(size); 
fread(buffer,size,1,file);
buffer = foo(buffer);

The result looks something like this in my debugger:

01326A18 5F4E8E19 5F0A0000

I want the first byte ( 01 ) to be int a.
The following 4 bytes are the first timestamp b (should be 5F186A32)
The following 4 bytes are the second timestamp c (should be 5F198E4E)
The 0A is supposed to be int d.

My Problem is that I can put the 1 into a, with (*buffer) & 0xff;,
but I'm not able to read the first timestamp correctly since its from second to 5th byte and not align with the int declaration of the buffer. If I print *(buffer +1) it gives me the second int and prints "198E4E5F" It would be better if I were able to target n byte from every position in my data.

thx in advance.

Upvotes: 0

Views: 138

Answers (2)

stark
stark

Reputation: 13189

Something like this will work on most little-endian platforms. Just fread the same way.

struct {
  uint8_t a;
  uint32_t timeStamp1;
  uint32_t timeStamp2;
  uint8_t d;
} buffer __attribute__((packed));
assert(sizeof buffer == 10);  /* check packing */

Upvotes: 2

Uzun Emre
Uzun Emre

Reputation: 151

If you set your buffer type as char* this will make it point to the 1 byte of chunks. Then if try to get buffer+2, it will return the second byte of the buffer, unlike int pointer which will return the 8th byte of the buffer. Do not forget to update your size in malloc call, since you get your memory with 1 byte chunks in this case. Also this link may be helpful.

Upvotes: 0

Related Questions