Converting String to Byte Array in PHP
To obtain a byte array from a string containing various characters, follow the approach outlined below.
Creating an Int Array with Unpack
Sparr provided an effective solution by utilizing the unpack function to create an array of integers. This technique allows you to represent each character as its corresponding numeric value. The example below demonstrates this approach:
$string = "The quick fox jumped over the lazy brown dog"; $byte_array = unpack('C*', $string);
In this example, the 'C' format character indicates that the array should contain unsigned integers ranging from 0 to 255. These values represent the ASCII codes for each character in the string.
Why the Int Presentation Matters
The reason you may require an integer presentation of characters in this case is to transmit a byte array to a Java server. Byte arrays in languages like C# commonly store byte values from 0 to 255. Therefore, using the aforementioned approach, you can obtain int[] in PHP, which can be directly cast to byte[] in C#.
Important Note
It is crucial to note that the array created by unpack is 1-based, meaning that the first element has the index 1 rather than 0. Keep this in mind when working with the array.
The above is the detailed content of How Can I Convert a PHP String to a Byte Array for Transmission to a Java Server?. For more information, please follow other related articles on the PHP Chinese website!