PHP Binary Data - Machine Independent

I have a little problem with the representation of binary data in PHP. I am developing communication between webserver (php) and foxtrot plc. Iam communicating at the bite level, but I cannot find the correct functions in php that fit all my needs ...

I am looking for an easy way to process and convert binary data to and from usint, sint, uint, int, udint, dint, real, string, etc. But I need it regardless of the web server machine, because the important part is plc,

The best solution is the pack / unpack function, but iam is missing some formats - for example signed long small endian order. And I need every single byte.

PLC 16 bit, so sizes: sint - 8bit / int - 16bit / dint - 32bit

// I need something like this
$lib->convertToBytes(65000); // result [0 => 11101000, 1 => 11111101]
$lib->convertToInt([0 => 11101000, 1 => 11111101]); // result 65000

// And this
$lib->convertToBytes(-65000); // result array
$lib->convertToBytes(658.2); // result array
$lib->convertToBytes(-320.8); // result array

      

My web server is 64 bit, so if I call:

decbin(-65000) // i get "1111111111111111111111111111111111111111111111110000001000011000" (64)
pack('l', -65000) // i get "\x18\x02\xff\xff" (4) - this seems good but i need machine independent representation - little endian byte order in every situation

      

Does anyone know a function / function / library that I can use?

Thanx

+3


source to share


1 answer


You are looking for the pack () function . It doesn't have signed / unsigned variants of all types because they are not needed, as the documentation notes:

"Note that the distinction between signed and unsigned values โ€‹โ€‹affects the unpack () function, where since the pack () function gives the same result for signed and unsigned formats."

To get individual bytes, you can use shifts and masks. This works by shifting the byte you want down low 8 bits, then using the AND operation to hide the other bits you don't want (by setting them to zero).

low byte: $val & 0xff;

Second byte: ($val >> 8) & 0xff;



Third byte: ($val >> 16) & 0xff;

To convert from single bytes to an integer, you do the opposite:

$val = $byte[0] | ($byte[1] << 8) | ($byte[2] << 16) ...

Etc.

+1


source







All Articles