yosra Posted April 11, 2013 Share Posted April 11, 2013 hellois there any function that convert a decimal to bytes thanks in advance Link to comment https://forums.phpfreaks.com/topic/276817-convert-to-bytes/ Share on other sites More sharing options...
Barand Posted April 11, 2013 Share Posted April 11, 2013 Can you give an example of what you are trying to achieve Link to comment https://forums.phpfreaks.com/topic/276817-convert-to-bytes/#findComment-1424118 Share on other sites More sharing options...
yosra Posted April 11, 2013 Author Share Posted April 11, 2013 i m tryin to to create library that format a message (protocol NXCP http://wiki.netxms.org/wiki/Communication_Protocol_Reference_Guide) ps: i m new in php thank u for ur quick answer NXCP.class.phpFetching info... Link to comment https://forums.phpfreaks.com/topic/276817-convert-to-bytes/#findComment-1424175 Share on other sites More sharing options...
lemmin Posted April 11, 2013 Share Posted April 11, 2013 I made this function a long time ago: $d: (number) The decimal string $bytes: (number) The number of bytes $little: (bool) Little or Big Endian function encode($d, $bytes, $little = true) { $string = NULL; $h = dechex($d); if ((strlen($h)%2)) $h = "0" . $h; if (!$little) { for ($i=0;$i<strlen($h);$i+=2) $string .= chr(hexdec($h[$i].$h[$i+1])); } else { for ($i=strlen($h)-1;$i>0;$i-=2) $string .= chr(hexdec($h[$i-1].$h[$i])); } $dif = $bytes-strlen($string); if ($dif < 0) { echo "Error: too big!"; return false; } $head = NULL; for ($i=$dif;$i>0;$i--) $head .= chr(0); return ($little) ? ($string.$head) : ($head.$string); } Link to comment https://forums.phpfreaks.com/topic/276817-convert-to-bytes/#findComment-1424183 Share on other sites More sharing options...
Barand Posted April 11, 2013 Share Posted April 11, 2013 unpack and pack may be worth a look Link to comment https://forums.phpfreaks.com/topic/276817-convert-to-bytes/#findComment-1424186 Share on other sites More sharing options...
lemmin Posted April 11, 2013 Share Posted April 11, 2013 I remember now that I used pack() (along with my function) in the generation of the same binary data, but I can't remember exactly why I had to. I guess there was a format it couldn't do. Anyway, pack() is definitely a better solution if it works. Link to comment https://forums.phpfreaks.com/topic/276817-convert-to-bytes/#findComment-1424190 Share on other sites More sharing options...
yosra Posted April 11, 2013 Author Share Posted April 11, 2013 thank u very much i will try it and i will get back to u Link to comment https://forums.phpfreaks.com/topic/276817-convert-to-bytes/#findComment-1424207 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.