2

I'm trying to send 0x01 HEX as Byte using the socket_write($socket, XXXX , 1); function.

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

2
  • 3
    pack()/unpack, or string escapes "\x01". Commented Oct 22, 2014 at 17:28
  • I have tried this: $data = pack('H*', "0x01"); socket_write($socket, $data , 1); ...but it's not working. Commented Oct 22, 2014 at 18:19

1 Answer 1

12

There are multiple alternatives:

  • When using the pack() function, the string argument to the H* format specifier should not include the 0x 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 integer 1, while chr() converts it into a string. The reversal (for socket reading) is ord().

  • The most prevalent alternative is using just using C-string escapes:

    "\x01"
    

    Or in octal notation:

    "\001"
    
  • hex2bin("01") works just like pack("H*") here. And there's bin2hex for the opposite direction.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.