note 107895 deleted from function.hexdec by danbrown

From: Date: Tue, 13 Mar 2012 17:22:45 +0000
Subject: note 107895 deleted from function.hexdec by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-186644@lists.php.net to get a copy of this message
Note Submitter: Timo ---- This class is a simple example to understand how a hex-Value is transformed to a signed-Integer. Use hecDecBin::hex2bin($strHexValue). You can echo each step of the way to understand how it performs the conversion. This helps when you are faced with negative numbers that are hex-coded. This is purely for learning / debug purpose. Fast / unlimeted conversion work better with: http://de3.php.net/manual/en/function.hexdec.php#97172 <?php class hexDecBin { public static function invertBin($strBin) { $newBin=""; for($i=0;$i<=strlen($strBin);$i++) { if(substr($strBin,$i,1)==1) { $newBin.="0"; } else { $newBin.="1"; } } return $newBin; } public static function isNegative($strBin) { if(substr($strBin,0,1)=="1") { return true; } else { return false; } } public static function hexDec($strHex) { $binVal=self::hex2bin($strHex); if(self::isNegative($binVal)) { $binVal=self::invertBin($binVal); $sign=-1; } else { $sign=1; } $num=(bindec($binVal)*$sign); if($sign==-1) $num=$num-1; return $num; } public static function hex2bin($strHex) { $base=(strlen($strHex)*4); $decVal=hexdec($strHex); $numValue=$decVal; $binValue=decbin($numValue); $additionalBytes=($base-strlen($binValue)); for($i=0;$i<$additionalBytes;$i++) { $binValue="0" . $binValue; } return $binValue; } } ?>

« previous php.notes (#186644) next »