Jump to content

convert to bytes


yosra

Recommended Posts

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.