Sunday, November 20, 2011

PHP Code to Convert Unsigned Word (Double Byte, 16-bit String) to Signed Integer

This is useful when one tries to read a two 8-bit unsigned char from binary file and then convert to a signed integer.

The following function is good to convert from 2 character byte string such as 0A, FE, etc., to a signed integer (tested working on both 32-bit and 64-bit Windows 7 IIS environment):




function read_short($s) { // assume $s is an array of (char 1, char 2)

$temp = (($s[0]&0x00ff)<<8) + ($s[1]&0x00ff);

if ($temp & (1 << 15) ) {
$temp = ($temp - (1 << 16)); // fill all bits with 1 from bit 17 onwards
}

return $temp;
}





This is the trick to process your 16-bit char (two unsigned char) in 32-bit/64-bit windows PHP environment.

No comments:

Post a Comment