PHP中的字符串到字节数组 [英] String to byte array in php

查看:88
本文介绍了PHP中的字符串到字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I get the byte array from some string which can contain numbers, letters and so on? If you are familiar with Java, I am looking for the same functionality of the getBytes() method.

我尝试了这样的代码段:

I tried a snippet like this one:

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

但没有成功,因此将不胜感激.

but without success, so any kind of help will be appreciated.

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

PS: Why do I need this at all!? Well, I need to send a byte array via fputs() to a server written in Java...

推荐答案

@Sparr是正确的,但是我想您期望C#中像byte[]这样的字节数组.这是与Sparr相同的解决方案,但是您希望每个charint表示形式(范围从0到255 )不是十六进制.您可以执行以下操作:

@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

通过使用var_dump,您可以看到元素是int(不是string ).

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) }

注意:输出数组是基于1的索引(正如注释中指出的那样)

Be careful: the output array is of 1-based index (as it was pointed out in the comment)

这篇关于PHP中的字符串到字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆