问题
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