3

I'm trying to send the binary representation of data through a PHP socket.

So if the number was 15, socket_write would send 00001111 as binary representation for 15.

How should I do this?

3
  • The amazing part is, at the interface layer, it gets sent as binary anyway! No need to convert. :D Commented Jan 14, 2013 at 7:07
  • @vanneto if you socket_write($fp, 15) it will be same as socket_write($fp, "15"), I.E. send the bytes 0x31 0x35 whereas as far as I can see he wants to send one byte 0x0F Commented Jan 14, 2013 at 7:09
  • Yeah, sorry for being confusing. I want to send the single byte representation of the data. I was doing socket_write($sock, 15) and it was sending the two bytes, which was confusing me. Commented Jan 14, 2013 at 7:25

2 Answers 2

4

Use the chr function:

socket_write( $fp, chr(15));

You can also use \x escapes with hex values:

socket_write( $fp, "\xff\xff\xff\xff" );

Would send 4 bytes, with values 255 on each.

Sign up to request clarification or add additional context in comments.

Comments

2

To generate a binary representation from arbitrary data use the pack() function.

Example:

$data = pack("v", 15); // "i" is unsigned little endian integer
socket_write($socket, $data);

See the manual page for more information on the various formats. There's also unpack() for the reverse functionality.

2 Comments

this will send 0x0F 0x00, you want "C" to just send 0x0F
Well, that's the correct binary representation for an unsigned little endian 16 bit integer. Additionally C is not valid for numbers > 255.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.