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 ?
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.