PHP convert integer to 32 bit (4 Byte) hex for socket programming

≯℡__Kan透↙ 提交于 2019-12-11 09:43:46

问题


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.

For example

3 = 00000003 15 = 0000000F

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.

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.


回答1:


i would do

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

this outputs

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

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

so in your example

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


来源:https://stackoverflow.com/questions/26787898/php-convert-integer-to-32-bit-4-byte-hex-for-socket-programming

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