PHP将整数转换为32位(4字节)十六进制以进行套接字编程 [英] PHP convert integer to 32 bit (4 Byte) hex for socket programming

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

问题描述

我需要将整数转换为4字节(32位)十六进制,以将其作为ACK发送到我当前尝试集成的设备。

I need to convert integer to a 4 byte (32 bit) hex for sending it as ACK to a device i am currently trying to integrate.

例如


3 = 00000003
15 = 0000000F

3 = 00000003 15 = 0000000F

检查 http://www.mathsisfun.com/binary-decimal- hexadecimal-converter.html
1.从下拉列表
中选择带符号的32位2.在 decomal文本框
中输入值3.在十六进制字段中检查值。

Check http://www.mathsisfun.com/binary-decimal-hexadecimal-converter.html 1. Select signed 32 bit from the dropdown 2. Enter the value in decomal text box 3. Check value in hex field.

我正在使用带有此参数的php pack函数,但根据设备的响应,这似乎不是正确的方法。

I am using php pack function with this parameter but based on the response from the device, it does not seem to be the correct approach.

$reply = pack(L*,$num);

这是正确的参数还是其他方法。
请建议。

Is this the correct parameter or there is some other way. Please suuggest.

推荐答案

我会这样做

$a = 15;
var_dump( sprintf("%08X", $a) );
$a = 3;
var_dump( sprintf("%08X", $a) );

此输出

string(8) "0000000F"
string(8) "00000003

08X 表示将一个8个字符的字符串填充为 0 (如果需要),并将参数视为十六进制。(

08X means make a 8 char string padded with 0 (if needed) with the argument being treated as hex. (Upper case letters)

所以在您的示例中

$reply = sprintf("%08X", $num)

这篇关于PHP将整数转换为32位(4字节)十六进制以进行套接字编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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