1

I wrote a C++ program which send POST data to php. My data is 123456 in binary, which is 0x0001e240.

My php file reads like

$f=fopen("php://input", "r");
if (!$f) die ("cannot open");
$data = fread($f, 4);
echo $data;

In my receiving program (in C++), I can see the echoed data is exactly 0x0001e240, so I believe php did accept a pure binary thing and saved into $data.

However, I want to get 123456 in php. I tried functions like bindec, hexdec, and so on but none of them works. How can I get the number from $data.

Also, do I need to care about endians in php? I am working locally now with windows environment but I will finally put my codes onto cloud.

Edit

$f=fopen("test.bin", "rb");
if (!$f) die ("cannot open");
$data = fread($f, 4);
echo $data;

where test.bin is a bin file which contains 0x0001e240. It seems that I got a string in $data which is composited with ASCII of 0x00, 0x01, 0xe2, and 0x40. How can I make them into a number value?

0

1 Answer 1

1

You can use unpack:

$num = unpack('n', $data);

Use an uppercase letter for an unsigned integer, and a v (or V) for little-endian. Yes, you have to worry about endianness. Just find out what it is and stick with it.

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

2 Comments

Thanks for your reply. But I got a notice saying "Notice: Array to string conversion" and I didn't get the number I want.
Oops I knew what I was wrong. and I should use N for 32bit. I think that works! thanks a lot!

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.