Search code examples
phppreg-replacepackunpack

4 bytes big-endian to int


I have a file that contains data (keywords) to interpret and starts with 4-bytes big endian to determine number of keywords. I can't seem to get the proper integer value from it.

$bytes = "00000103";
$keywords = preg_replace("/(.{2})(.{2})(.{2})(.{2})/u", "\x$1\x$2\x$3\x$4", $bytes);
var_dump($keywords);
$unpacked = unpack("N", $keywords);
var_dump($unpacked);

Outputs (incorrect):

string(16) "\x00\x00\x01\x03"
array(1) {
  [1]=>
  int(1551380528)
}

For testing purposes, I change the $keywords variable to:

$bytes = "\x00\x00\x01\x03";

It outputs (correct):

string(4) ""
array(1) {
  [1]=>
  int(259)
}

How do I change the data-type of $keywords? Searched a lot, but can't get it to work unfortunately.

PS. After posting, it doesn't show the 2 characters (boxes with questionmarks) in them in the correct output for string(4).


Solution

  • You can simply use the hexdec-function:

    $bytes = "00000103";
    $dec = hexdec($bytes);
    var_dump($dec);  //int(259)