tzortzik
tzortzik

Reputation: 5133

PHP conversions between binary, octal, decimal and hexadecimal with floating number

I would like to convert floating numbers (eg. 152.35964) between binary, octal, decimal and hexadecimal numbers.

I googled but I didn't found anything relative to what I want. All that I have found was in documentation but these functions (bindec(), octdec(), binhex(), etc and base_convert()) operates just with integers and I need floats or doubles.

Thank you!

Upvotes: 3

Views: 2438

Answers (2)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798884

The hard way:

$signmap = Array(
  -1 => '-',
  1 => ''
);

function fractur($f)
{
  if ($f < 0)
  {
    $sign = -1;
    $f = -$f;
  } else {
    $sign = 1;
  };
  $intp = floor($f);
  $fracp = $f - $intp;
  return Array($sign, $intp, $fracp);
};

function float2var($f, $spec)
{
  global $signmap;
  list($sign, $intp, $fracp) = fractur($f);
  $format = sprintf('%%s%s.%s', $spec, $spec);
  $ret = sprintf($format, $signmap[$sign], $intp, $fracp * 16777216);
  // 64-bit systems can use the next line instead
  //$ret = sprintf($format, $signmap[$sign], $intp, $fracp * 18014398509481984);
  return rtrim(rtrim($ret, '0'), '.');
};

function float2bin($f)
{
  return float2var($f, '%b');
};

function float2oct($f)
{
  return float2var($f, '%o');
};

function float2hex($f)
{
  return float2var($f, '%x');
};

var_dump(float2bin(10.5));
var_dump(float2bin(10));
var_dump(float2bin(-2.5));
var_dump(float2bin(2.5));
var_dump(float2oct(2.5));
var_dump(float2hex(2.5));

Upvotes: 0

Mark Baker
Mark Baker

Reputation: 212452

Have a look at Nstiac's post on this page of the PHP manual. He provides a pair of routines for converting a float to IEEE 754 single-precision 32-bit and its reverse.

It shows a hex value of "43185c11" for your quoted example of 152.35964. Is this what you're expecting to see.

Or an alternative version of that logic:

$value = 152.35964;
var_dump($value);

$packedValue = pack('f',$value);

$packedLength = strlen($packedValue);
$packedHexDisplay = '';
for($i = $packedLength-1; $i >= 0; --$i) {
    $packedHexDisplay .= str_pad(dechex(ord($packedValue[$i])),2,'0',STR_PAD_LEFT);
}
var_dump($packedHexDisplay);

$unpackedValue = unpack('f',$packedValue);
var_dump($unpackedValue);

Upvotes: 1

Related Questions