PHP convert hex to byte

随声附和 提交于 2019-12-21 21:39:18

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/26513381/php-convert-hex-to-byte

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!