Home >Backend Development >PHP Tutorial >How Can I Convert a PHP String into a Byte Array Using `unpack()`?

How Can I Convert a PHP String into a Byte Array Using `unpack()`?

Susan Sarandon
Susan SarandonOriginal
2024-12-04 06:02:13659browse

How Can I Convert a PHP String into a Byte Array Using `unpack()`?

Converting a String to a Byte Array in PHP

In PHP, you may encounter the need to convert a string into a byte array, especially when interfacing with systems expecting binary data formats.

GetBytes() Equivalent in PHP

Similar to Java's getBytes() method, PHP offers the unpack() function to accomplish this task. Unlike getBytes(), which returns a byte array representing the string's Unicode code points, unpack() allows you to specify a custom format to extract specific data.

Unpacking a String into an Integer Array

To obtain an integer array representing the byte values of a string, use the following unpack() format:

$byte_array = unpack('C*', $string);

The format string 'C*' indicates that we want to unpack a sequence of unsigned characters (in ranges [0, 255]), representing the byte values of the string.

Example

Let's take the example string: "The quick fox jumped over the lazy brown dog". Using the above approach, we can obtain the corresponding byte array:

$string = "The quick fox jumped over the lazy brown dog";
$byte_array = unpack('C*', $string);

var_dump($byte_array);

Output:

array(44) {
  [1] => int(84)
  [2] => int(104)
  [3] => int(101)
  [4] => int(32)
  [5] => int(113)
  [6] => int(117)
  [7] => int(105)
  [8] => int(99)
  [9] => int(107)
  [10] => int(32)
  [11] => int(102)
  [12] => int(111)
  [13] => int(120)
  [14] => int(32)
  [15] => int(106)
  [16] => int(117)
  [17] => int(109)
  [18] => int(112)
  [19] => int(101)
  [20] => int(100)
  [21] => int(32)
  [22] => int(111)
  [23] => int(118)
  [24] => int(101)
  [25] => int(114)
  [26] => int(32)
  [27] => int(116)
  [28] => int(104)
  [29] => int(101)
  [30] => int(32)
  [31] => int(108)
  [32] => int(97)
  [33] => int(122)
  [34] => int(121)
  [35] => int(32)
  [36] => int(98)
  [37] => int(114)
  [38] => int(111)
  [39] => int(119)
  [40] => int(110)
  [41] => int(32)
  [42] => int(100)
  [43] => int(111)
  [44] => int(103)
}

As you can see, the output array contains the byte values of each character in the string, indexed from 1.

The above is the detailed content of How Can I Convert a PHP String into a Byte Array Using `unpack()`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn