<?PHP/** * byte array and string conversion class * @author ZT*/classBytes {/** * Convert a string string to a byte array * @param $str the string to be converted * @param $bytes destination byte array*/ Public Static functionGetBytes$str) { $len=strlen($str); $bytes=Array(); for($i= 0;$i<$len;$i++) { if(Ord($str[$i]) >= 128){ $byte=Ord($str[$i])-256; }Else{ $byte=Ord($str[$i]); } $bytes[] =$byte ; } return $bytes; } /** * Convert byte arrays to data of type String * @param $bytes byte array * @param $str target String * @return A String type of data*/ Public Static functionTOSTR ($bytes) { $str= ' '; foreach($bytes as $ch) { $str.=CHR($ch); } return $str; } /** convert an int to a byte array * @param $byt destination byte array * @param $val the string to be converted*/ Public Static functionIntegertobytes ($val) { $byt=Array(); $byt[0] = ($val& 0xFF); $byt[1] = ($val>> 8 & 0xFF); $byt[2] = ($val>> & 0xFF); $byt[3] = ($val>> & 0xFF); return $byt; } /** * Reads an integer type of data from the location specified in the byte array * @param $bytes byte array * @param $position the specified start position * @return An integer type of Data*/ Public Static functionBytestointeger ($bytes,$position) { $val= 0; $val=$bytes[$position+ 3] & 0xFF; $val<<= 8; $val|=$bytes[$position+ 2] & 0xFF; $val<<= 8; $val|=$bytes[$position+ 1] & 0xFF; $val<<= 8; $val|=$bytes[$position] & 0xFF; return $val; } /** * Convert a Shor string to a byte array * @param $byt destination byte array * @param $val string to convert*/ Public Static functionShorttobytes ($val) { $byt=Array(); $byt[0] = ($val& 0xFF); $byt[1] = ($val>> 8 & 0xFF); return $byt; } /** * Reads a short type of data from the location specified in the byte array. * @param $bytes byte array * @param $position specified start position * @return A short type of data*/ Public Static functionBytestoshort ($bytes,$position) { $val= 0; $val=$bytes[$position+ 1] & 0xFF; $val=$val<< 8; $val|=$bytes[$position] & 0xFF; return $val; } }
PHP byte array and string conversion class