String to byte array in php
Solution 1:
@Sparr is right, but I guess you expected byte array like byte[]
in C#. It's the same solution as Sparr did but instead of HEX you expected int
presentation (range from 0 to 255) of each char
. You can do as follows:
$byte_array = unpack('C*', 'The quick fox jumped over the lazy brown dog');
var_dump($byte_array); // $byte_array should be int[] which can be converted
// to byte[] in C# since values are range of 0 - 255
By using var_dump
you can see that elements are int
(not string
).
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) }
Be careful: the output array is of 1-based index (as it was pointed out in the comment)
Solution 2:
print_r(unpack("H*","The quick fox jumped over the lazy brown dog"))
Array ( [1] => 54686520717569636b20666f78206a756d706564206f76657220746865206c617a792062726f776e20646f67 )
T = 0x54, h = 0x68, ...
You can split the result into two-hex-character chunks if necessary.
Solution 3:
PHP has no explicit byte
type, but its string
is already the equivalent of Java's byte array. You can safely write fputs($connection, "The quick brown fox …")
. The only thing you must be aware of is character encoding, they must be the same on both sides. Use mb_convert_encoding() when in doubt.
Solution 4:
You could try this:
$in_str = 'this is a test';
$hex_ary = array();
foreach (str_split($in_str) as $chr) {
$hex_ary[] = sprintf("%02X", ord($chr));
}
echo implode(' ',$hex_ary);
Solution 5:
In PHP, strings are bytestreams. What exactly are you trying to do?
Re: edit
Ps. Why do I need this at all!? Well I need to send via fputs() bytearray to server written in java...
fputs
takes a string as argument. Most likely, you just need to pass your string to it. On the Java side of things, you should decode the data in whatever encoding, you're using in php (the default is iso-8859-1).