123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- <?php
- namespace loyalsoft;
- /**
- * byte数组与字符串转化类
- * @version
- * 1.0.0 Created at 2017-6-12. by --gwang
- * @author gwang (mail@wanggangzero.cn)
- * @copyright ? 2017-6-12, SJZ LoyalSoft Corporation & gwang. All rights reserved.
- */
- class Bytes {
- /**
- * 转换一个String字符串为byte数组
- * @param $str 需要转换的字符串
- * @param $bytes 目标byte数组
- */
- public static function getBytes(string $string): array {
- $bytes = array();
- for ($i = 0;
- $i < strlen($string);
- $i++) {
- $bytes[] = ord($string[$i]);
- }
- return $bytes;
- }
- /**
- * 将字节数组转化为String类型的数据
- * @param $bytes 字节数组
- * @param $str 目标字符串
- * @return 一个String类型的数据
- */
- public static function toStr(array $bytes): string {
- $str = '';
- foreach ($bytes as $ch) {
- $str .= chr($ch);
- }
- return $str;
- }
- /**
- * 转换一个int为byte数组
- * @param $byt 目标byte数组
- * @param $val 需要转换的字符串
- */
- public static function integerToBytes(int $val): array {
- $byt = array();
- $byt[0] = ($val & 0xff);
- $byt[1] = ($val >> 8 & 0xff);
- $byt[2] = ($val >> 16 & 0xff);
- $byt[3] = ($val >> 24 & 0xff);
- return $byt;
- }
- /**
- * 从字节数组中指定的位置读取一个Integer类型的数据
- * @param $bytes 字节数组
- * @param $position 指定的开始位置
- * @return 一个Integer类型的数据
- */
- public static function bytesToInteger(array $bytes, int $position): int {
- // $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;
- }
- /**
- * 转换一个shor字符串为byte数组
- * @param $byt 目标byte数组
- * @param $val 需要转换的字符串
- */
- public static function shortToBytes(int $val): array {
- $byt = array();
- $byt[0] = ($val & 0xff);
- $byt[1] = ($val >> 8 & 0xff);
- return $byt;
- }
- /**
- * 从字节数组中指定的位置读取一个Short类型的数据。
- * @param $bytes 字节数组
- * @param $position 指定的开始位置
- * @return 一个Short类型的数据
- */
- public static function bytesToShort(array $bytes, int $position): int {
- // $val = 0;
- $val = $bytes[$position + 1] & 0xFF;
- $val <<= 8;
- $val |= $bytes[$position] & 0xFF;
- return $val;
- }
- }
|