2

Hey all so I've ran into a bit of a problem, from PHP I have to read some data from a binary file where SPACE is of the utmost importance so they've used 24 bit integers in places.

Now for most of the data I can read with unpack however pack/unpack does not support 24 bit int's :s

I thought I could perhaps simple read the data (say for example 000104) as H* and have it read into a var that would be correct.

// example binary data say I had the following 3 bytes in a binary file
// 0x00, 0x01, 0x04

$buffer = unpack("H*", $data);

// this should equate to 260 in base 10 however unpacking as H* will not get
// this value.

// now we can't unpack as N as it requires 0x4 bytes of data and n being a 16 bit int
// is too short.

Has anyone had to deal with this before? Any solutions? advice?

Joe
  • 49
  • 1
  • 8

1 Answers1

0

If the file has only 3 bytes as above, the easiest way is padding as @DaveRandom said. But if it's a long file this method becomes inefficient.

In this case you can read each element as a char and a short, after that repack it by bitwise operators.

Or you can read along 12 bytes as 3 longs and then splits it into 4 groups of 3 bytes with bitwise operators. The remaining bytes will be extracted by the above 2 methods. This will be the fastest solution on large data.

unsigned int i, j;
unsigned int dataOut[SIZE];

for (i = 0, j = 0; j < size; i += 4, j += 3)
{
    dataOut[i]     = dataIn[j] >> 8;
    dataOut[i + 1] = ((dataIn[j] & 0xff) << 16) | (dataIn[j + 1] >> 16);
    dataOut[i + 2] = ((dataIn[j + 1] & 0xffff) << 8) | (dataIn[j + 2] >> 24);
    dataOut[i + 3] = dataIn[j + 2] & 0xffffff;
}

The following question has an example code to unpack a string of 24/48bits too

Community
  • 1
  • 1
phuclv
  • 37,963
  • 15
  • 156
  • 475