3

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!

Gumbo
  • 643,351
  • 109
  • 780
  • 844
tzortzik
  • 4,993
  • 9
  • 57
  • 88

2 Answers2

1

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);
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
0

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));
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358