Bytes.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. namespace loyalsoft;
  3. /**
  4. * byte数组与字符串转化类
  5. * @version
  6. * 1.0.0 Created at 2017-6-12. by --gwang
  7. * @author gwang (mail@wanggangzero.cn)
  8. * @copyright ? 2017-6-12, SJZ LoyalSoft Corporation & gwang. All rights reserved.
  9. */
  10. class Bytes {
  11. /**
  12. * 转换一个String字符串为byte数组
  13. * @param $str 需要转换的字符串
  14. * @param $bytes 目标byte数组
  15. */
  16. public static function getBytes(string $string): array {
  17. $bytes = array();
  18. for ($i = 0;
  19. $i < strlen($string);
  20. $i++) {
  21. $bytes[] = ord($string[$i]);
  22. }
  23. return $bytes;
  24. }
  25. /**
  26. * 将字节数组转化为String类型的数据
  27. * @param $bytes 字节数组
  28. * @param $str 目标字符串
  29. * @return 一个String类型的数据
  30. */
  31. public static function toStr(array $bytes): string {
  32. $str = '';
  33. foreach ($bytes as $ch) {
  34. $str .= chr($ch);
  35. }
  36. return $str;
  37. }
  38. /**
  39. * 转换一个int为byte数组
  40. * @param $byt 目标byte数组
  41. * @param $val 需要转换的字符串
  42. */
  43. public static function integerToBytes(int $val): array {
  44. $byt = array();
  45. $byt[0] = ($val & 0xff);
  46. $byt[1] = ($val >> 8 & 0xff);
  47. $byt[2] = ($val >> 16 & 0xff);
  48. $byt[3] = ($val >> 24 & 0xff);
  49. return $byt;
  50. }
  51. /**
  52. * 从字节数组中指定的位置读取一个Integer类型的数据
  53. * @param $bytes 字节数组
  54. * @param $position 指定的开始位置
  55. * @return 一个Integer类型的数据
  56. */
  57. public static function bytesToInteger(array $bytes, int $position): int {
  58. // $val = 0;
  59. $val = $bytes[$position + 3] & 0xff;
  60. $val <<= 8;
  61. $val |= $bytes[$position + 2] & 0xff;
  62. $val <<= 8;
  63. $val |= $bytes[$position + 1] & 0xff;
  64. $val <<= 8;
  65. $val |= $bytes[$position] & 0xff;
  66. return $val;
  67. }
  68. /**
  69. * 转换一个shor字符串为byte数组
  70. * @param $byt 目标byte数组
  71. * @param $val 需要转换的字符串
  72. */
  73. public static function shortToBytes(int $val): array {
  74. $byt = array();
  75. $byt[0] = ($val & 0xff);
  76. $byt[1] = ($val >> 8 & 0xff);
  77. return $byt;
  78. }
  79. /**
  80. * 从字节数组中指定的位置读取一个Short类型的数据。
  81. * @param $bytes 字节数组
  82. * @param $position 指定的开始位置
  83. * @return 一个Short类型的数据
  84. */
  85. public static function bytesToShort(array $bytes, int $position): int {
  86. // $val = 0;
  87. $val = $bytes[$position + 1] & 0xFF;
  88. $val <<= 8;
  89. $val |= $bytes[$position] & 0xFF;
  90. return $val;
  91. }
  92. }