PHP将十六进制转换为字节 [英] PHP convert hex to byte

查看:2370
本文介绍了PHP将十六进制转换为字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过socket_write($ socket,XXXX,1)发送0x01 HEX作为Byte。



有一部分文档:
$ b

...如果是,服务器将回复模块0x01,如果没有 - 重播0x00,服务器必须发送答案 - 1字节
,十六进制格式



有什么解决方案可以通过PHP来完成?

解决方案

有多种选择:


  • 当使用 pack() 函数时,字符串参数至 H * 格式说明符应包含 0x 前缀。

      pack(H *,01)


  • 要将单个十六进制数字转换为字节,您还可以使用 <$

      chr(0x01)$ b code> chr() 

    b

    这里PHP首先将十六进制文件 0x01 解释为普通整数 1 ,而chr()将它转换为串。反转(用于套接字读取)是 ord() .doublerel =noreferrer> C字符串转义:

     \x01

    或以八进制表示法:

     \001


  • hex2bin(01) pack(H * )这里。有相反的方向 bin2hex



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?

解决方案

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.

这篇关于PHP将十六进制转换为字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆