: This article mainly introduces examples of conversion of php strings and byte arrays. if you are interested in the PHP Tutorial, please refer. Php string and byte array conversion class example
/**
* Byte array and string conversion class
*/
Class Bytes {
/**
* Convert a String to a byte array.
* @ Param $ str the string to be converted
* @ Param $ bytes target byte array
* @ Author Zikie
*/
Public static function getBytes ($ string ){
$ Bytes = array ();
For ($ I = 0; $ I <strlen ($ string); $ I ++ ){
$ Bytes [] = ord ($ string [$ I]);
}
Return $ bytes;
}
/**
* Convert byte arrays to String-type data.
* @ Param $ bytes byte array
* @ Param $ str target string
* @ Return a String type data
*/
Public static function toStr ($ bytes ){
$ Str = '';
Foreach ($ bytes as $ ch ){
$ Str. = chr ($ ch );
}
Return $ str;
}
/**
* Convert an int to a byte array.
* @ Param $ byt the target byte array
* @ Param $ val: string to be converted
*
*/
Public static function integerToBytes ($ val ){
$ Byt = array ();
$ Byt [0] = ($ val & 0xff );
$ Byt [1] = ($ val> 8 & 0xff );
$ Byt [2] = ($ val> 16 & 0xff );
$ Byt [3] = ($ val> 24 & 0xff );
Return $ byt;
}
/**
* Read an Integer data from the specified position in the byte array
* @ Param $ bytes byte array
* @ Param $ position specifies the start position.
* @ Return an Integer data type
*/
Public static function bytesToInteger ($ 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 the target byte array
* @ Param $ val: string to be converted
*
*/
Public static function extends tobytes ($ val ){
$ Byt = array ();
$ Byt [0] = ($ val & 0xff );
$ Byt [1] = ($ val> 8 & 0xff );
Return $ byt;
}
/**
* Read a Short type data from the specified position in the byte array.
* @ Param $ bytes byte array
* @ Param $ position specifies the start position.
* @ Return a Short type data
*/
Public static function bytesToShort ($ bytes, $ position ){
$ Val = 0;
$ Val = $ bytes [$ position + 1] & 0xFF;
$ Val = $ val <8;
$ Val | = $ bytes [$ position] & 0xFF;
Return $ val;
}
}
?>
The above describes the php string and byte array conversion examples, including some content, hope to be helpful to friends who are interested in the PHP Tutorial.