Hi, I have been trying to perfect a method of converting an integer valued 0-65535 into 2 bytes of ascii, and vice versa. I produced a couple of functions which rely on the ord and char functions to do the conversions, but I am noticing extremely unusual bugs.
//-----makeUshort
//str makeUshort(int ushort);
//
function makeUshort($intIn){
//echo "intIn is $intIn\n";
//if it out of range
if($intIn > 65535 or $intIn < 0)
//return false
return false;
//get the input as binary
$asBin = decbin($intIn);
echo "asBin is $asBin\n";
$byteOne = bindec(substr($asBin,0,8));
echo "byteOne is $byteOne\n";
$byteTwo = bindec(substr($asBin,8));
echo "byteTwo is $byteTwo\n";
//get the characters and concatenate them
$strOut = sprintf("%c%c",$byteOne,$byteTwo);
echo "strOut is '$strOut'\n";
//return the 2 byte string
return $strOut;
}
//-----getUshort
//int getUshort(str ushort);
//
function getUshort($strIn){
echo "strIn is '$strIn'\n";
$msB = ord($strIn{1}); //msB most significant Byte (byte 2)
echo "msB is '$msB'\n";
$lsB = ord($strIn); //lsB list significant Byte (byte 1)
echo "lsB is '$lsB'\n";
$intOut = $msB * 256 + $lsB;
echo "intOut is '$intOut'\n";
return $intOut;
}
The outputs are unusual, for values below 1024 the result was correct in a previous version (seems almost random now). 1024 and above have odd results that I can't understand. I initially thought about the byte order, so I made it multiply the first character by 256 instead, in getUshort (knowing that the way they are formed shouldn't make that correct). This just made it all incorrect. In makeUshort I tried using sprintf to pad the output of dec2bin to add initial 0s so that it was 16 digits long - and then using char twice. But the results were the same as using sprintf to convert into ascii - as I am doing now. I can't figure out the problem in my functions and have about 10 test versions of each messing up the working directory. Can anyone see an alternate solution, or problems in my code that might be causing the bug/s?
I was using this php to test it, (expecting the output to be the same as the input)
<?php
echo getushort(makeUshort(52)) ."\n". getushort(makeUshort(33169)) ."\n\n";
echo getushort(makeUshort(1023)) ."\n". getushort(makeUshort(1024));
?>
and got (without debug from inside the functions):
52
37249
1023
128