在PHP中以十六进制形式发送 [英] Send as hex in PHP

查看:264
本文介绍了在PHP中以十六进制形式发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力将十六进制值发送到连接到我的PHP套接字服务器的设备上.

I am struggeling a little to send a hex value to a device connected to my PHP socket server.

我有此代码:

<?PHP

# 7e hex = 126 decimal

$str1 = "\x7e\x00MyData";
sendToDevice($str1); // works :-)
# will send "~<NUL>MyData" and the device sends expected result back

$dec = 126;
$hex = dechex($dec);
$str2 = $hex . "\x00MyData";
sendToDevice($str2); // does not work :-/
# will send "7eMyData" and the device sends nothing back

$dec = 126;
$hex = dechex($dec);
$str3 = "\x$hex\x00MyData";
sendToDevice($str3); // does not work :-/
# will send "\x7e<NUL>MyData" and the device sends error report back

?>

如何发送它,使其与 $ str1 一样工作?

How can I sent it so it works as with $str1 ?

推荐答案

这是由于PHP解析字符串的方式所致.当PHP解析第一个字符串时,它会看到"\ x7e"并说我需要将其转换为十六进制代码为7e的字符.在其他情况下,它会看到"\ x",并尝试将其转换在获得"7e"之前,所以它不知道该怎么办.

This is due to the way PHP parses the strings. When PHP parses the first string, it sees the "\x7e" and says "I need to convert this to the character who's code is 7e in hex. In the other scenarios, it sees the "\x", and tries to convert that before it gets the "7e", so it doesn't know what to do.

PHP不会第二次解析字符串.

PHP doesn't parse the strings a second time.

在这种情况下,您需要执行的操作是将您的数字转换为字符表示形式,而不是十六进制代码.您需要的是 chr()函数.您应该能够执行以下操作:

What you need to do in this situation is convert your number to the character representation, rather than the hex code. What you need is the chr() function. You should be able to do something like this:

$dec = 127;
$str2 = chr($dec) . "\x00MyData";
sendToDevice($str2);

请注意,它完全跳过了十六进制转换.还要注意,这仅在$ dec的值小于等于255时有效.如果您具有较高的值,则需要创建自己的函数以将其分解为几个字符.

Note that it's skipping the hex conversion altogether. Also note that this only works if your $dec value is <= 255. If you've got higher values, you'll need to create your own function to break it up in to several characters.

这篇关于在PHP中以十六进制形式发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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