Search code examples
phppack24-bit

pack list of 24-bit integers in php


Context: I'm reading/writing data, which for storage reason comes as 24-bit integers (signed or unsigned doesn't matter as they're actually 8 octal values). I need to store/read a large number of these integers with pack and unpack. The application is space-critical so using 32-bit integers is not desirable.

However, pack doesn't seem to have an option for 24-bit integers. How does one deal with this? I currently use a custom function

function pack24bit($n) {
    $b3 = $n%256;
    $b2 = $n/256;
    $b1 = $b2/256;
    $b2 = $b2%256;
    return pack('CCC',$b1,$b2,$b3);
}

and

function unpack24bit($packed) {
    $arr = unpack('C3b',$packed);
    return 256*(256*$arr['b1']+$arr['b2'])+$arr['b3'];
}

but maybe there are more direct ways?


Solution

  • There is no such thing as a 24-bit integer on any modern CPU that I'm aware of, which is why your desired packing is not directly supported.

    I recommend packing your bytes individually, as you suggested. Be mindful of endianness.