php中的字符串到字节数组

php中的字符串到字节数组

如何从包含数字,字母等的字符串中获取字节数组?如果您熟悉Java,我正在寻找getBytes()方法的相同功能。

我尝试了一个像这样的片段:

for($i = 0; $i < strlen($msg); $i++){
    $data.=ord($msg[$i]);
        //or $data[]=ord($msg[$1]); }

但没有成功,所以任何形式的帮助将不胜感激。

PS:为什么我需要这个!?好吧,我需要通过fputs()将一个字节数组发送到用Java编写的服务器...


温温酱
浏览 633回答 3
3回答

青春有我

我猜你byte[]在C#中期望字节数组。它与Sparr的解决方案相同,但不是HEX,而是预期每种方式的int呈现方式(范围从0到255)char。你可以这样做:$byte_array = unpack('C*', 'The quick fox jumped over the lazy brown dog');var_dump($byte_array);&nbsp; // $byte_array should be int[] which can be converted&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // to byte[] in C# since values are range of 0 - 255通过使用,var_dump您可以看到元素是int(不是string)。&nbsp; &nbsp;array(44) {&nbsp; [1]=>&nbsp; int(84)&nbsp; [2]=>&nbsp; int(104) [3]=>&nbsp; int(101) [4]=>&nbsp; int(32)[5]=> int(113)&nbsp; [6]=>&nbsp; int(117) [7]=>&nbsp; int(105) [8]=>&nbsp; int(99)&nbsp; [9]=>&nbsp; int(107)[10]=> int(32)&nbsp; [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)&nbsp; [22]=> int(111) [23]=> int(118) [24]=> int(101)[25]=> int(114) [26]=> int(32)&nbsp; [27]=> int(116) [28]=> int(104) [29]=> int(101)[30]=> int(32)&nbsp; [31]=> int(108) [32]=> int(97)&nbsp; [33]=> int(122) [34]=> int(121)[35]=> int(32)&nbsp; [36]=> int(98)&nbsp; [37]=> int(114) [38]=> int(111) [39]=> int(119)[40]=> int(110) [41]=> int(32)&nbsp; [42]=> int(100) [43]=> int(111) [44]=> int(103) }注意:输出数组是基于1的索引(正如在注释中指出的那样)

交互式爱情

print_r(unpack("H*","The&nbsp;quick&nbsp;fox&nbsp;jumped&nbsp;over&nbsp;the&nbsp;lazy&nbsp;brown&nbsp;dog"))Array&nbsp;(&nbsp;[1]&nbsp;=>&nbsp;54686520717569636b20666f78206a756d706564206f76657220746865206c617a792062726f776e20646f67&nbsp;)T = 0x54,h = 0x68,......如有必要,可以将结果拆分为双十六进制字符块。

海绵宝宝撒

你可以试试这个:$in_str&nbsp;=&nbsp;'this&nbsp;is&nbsp;a&nbsp;test';$hex_ary&nbsp;=&nbsp;array();foreach&nbsp;(str_split($in_str)&nbsp;as&nbsp;$chr)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;$hex_ary[]&nbsp;=&nbsp;sprintf("%02X",&nbsp;ord($chr));}echo&nbsp;implode('&nbsp;',$hex_ary);
打开App,查看更多内容
随时随地看视频慕课网APP