Converting bytes retrieved over a php socket to a integer

ぃ、小莉子 提交于 2019-12-24 07:35:28

问题


I am using the netty API to create a Java server which sends if a client programm sends anything to the server a number like 5. It is a integer with 4 bytes. I think it should be the same like writing an integer into an OutputStream. So I want to receive the integer now by php. But if I call socket_read it outputs nothing helpfull because it does not convert the 4 bytes into a integer. It just uses this as text.

If I send a char it works so I need a way in php to convert it.

Or would it be the best to convert all into text clientside, so all is text-based. I think maybe I have to stick with a text-based or binary output.

EDIT: Another question related to this is, let's say I have 4 bytes in java. How can I build a Integer? Do I have to concat the 4 bytes?

Example:

Byte 1: 00000000

Byte 2: 00010000

Byte 3: 00000101

Byte 4: 00000001

Result: 00000000 00010000 00000101 00000001

Would this be correct?


回答1:


You probably want to use the unpack function. Something like:

$data = socket_read($sock,4);
$x = unpack("N",$data);


来源:https://stackoverflow.com/questions/14510817/converting-bytes-retrieved-over-a-php-socket-to-a-integer

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