zend framework - Convert binary or hexadecimal string using php into 32-bit float value. Big endian \ Little endian -
how can convert 32-bit binary string 00111001101010000101110000100010
or hexadecimal string 39a85c22
float value?
for use in zend framework.
i use following class. usage output 0.00032112101325765
3 times:
$x = new application_model_binary("39a85c22"); echo "\n".$x->getfloatfrombits(0, application_model_binary::endian_big); $x = new application_model_binary("00111001101010000101110000100010", false); echo "\n".$x->getfloatfrombits(0, application_model_binary::endian_big); $x = new application_model_binary("225ca839"); echo "\n".$x->getfloatfrombits(0, application_model_binary::endian_little);
and class
class application_model_binary { const endian_big = 0; const endian_little = 1; private $bin; public function __construct($string, $as_hex = true) { if($as_hex){ $this->bin = $this->hex2bin($string); }else{ $this->bin = $string; } } /** * convert hex-string bin-string * @param string $data * @return string */ private function hex2bin($data){ $encoded = ''; $data_arr = str_split($data, 2); foreach($data_arr $val){ $binary = base_convert($val, 16, 2); $encoded .= str_pad($binary, 8, '0', str_pad_left); } return $encoded; } /** * integer value out of current binary * @param integer $start offset * @param integer $length length * @return integer */ public function getvaluefrombits($start, $length = null){ return base_convert($this->getbinaryslice($start, $length), 2, 10); } /** * particular piece of current binary * @param integer $start * @param integer $length * @return string */ public function getbinaryslice($start, $length = null){ if($length){ return substr($this->bin, $start, $length); }else{ return substr($this->bin, $start); } } /** * bits count * @return type */ public function bits(){ return strlen($this->bin); } /** * 32-bit float value @ particular offset @ specific endian type * @param integer $offset offset * @return float */ public function getfloatfrombits($offset, $mode = self::endian_big){ if($mode === self::endian_big){ $sign = $this->getbinaryslice($offset, 1); $exp = $this->getbinaryslice($offset + 1, 8); $mantissa = "1" . $this->getbinaryslice($offset + 9, 23); }else{ $sign = $this->getbinaryslice($offset + 24, 1); $exp = $this->getbinaryslice($offset + 25, 7).$this->getbinaryslice($offset + 16, 1); $mantissa = "1" . $this->getbinaryslice($offset + 17, 7) . $this->getbinaryslice($offset + 8, 8) . $this->getbinaryslice($offset, 8); } $mantissa = str_split($mantissa); $exp = bindec($exp) - 127; $base = 0; ($i = 0; $i < 24; $i++) { $base += (1 / pow(2, $i))*$mantissa[$i]; } return $base * pow(2, $exp) * ($sign*-2+1); } }
Comments
Post a Comment