PHP convert hex to byte
There are multiple alternatives:
-
When using the
pack()
function, the string argument to theH*
format specifier should not include the0x
prefix.pack("H*", "01")
-
To convert a single hex-number into a byte you can also use
chr()
.chr(0x01)
Here PHP first interprets the hex-literal
0x01
into a plain integer1
, while chr() converts it into a string. The reversal (for socket reading) isord()
. -
The most prevalent alternative is using just using C-string escapes:
"\x01"
Or in octal notation:
"\001"
hex2bin("01")
works just likepack("H*")
here. And there'sbin2hex
for the opposite direction.
![Admin](/assets/logo_square_200-5d0d61d6853298bd2a4fe063103715b4daf2819fc21225efa21dfb93e61952ea.png)
Admin
Updated on June 04, 2022Comments
-
Admin about 2 years
I'm trying to send 0x01 HEX as Byte by socket_write($socket, XXXX , 1);
There is part of documentation:
"...If yes, server will reply to module 0x01, if not – replay 0x00. Server must send answer – 1 Byte in HEX format"
Is there any solution to do this by PHP?