问题
I am struggeling a little to send a hex value to a device connected to my PHP socket server.
I have this code:
<?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
?>
How can I sent it so it works as with $str1 ?
回答1:
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 doesn't parse the strings a second time.
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);
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.
回答2:
The 3rd approach is not so far away. But a remaining problem is, that the \x
will be interpeted as an escape sequence in double quoted strings. Workaround: Use single quotes:
$dec = 127;
$hex = dechex($dec);
$str3 = '\x' . $hex . '\x00MyData';
sendToDevice($str3);
A simpler solution that does not need dechex()
would be to use sprintf() as it has internal support for converting decimal values to hex values. Now it can be even a one-liner:
sendToDevice(sprintf('\x%x\x00MyData', $dec));
来源:https://stackoverflow.com/questions/17566378/send-as-hex-in-php