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!

2
  • 1
    What would you expect for 152.35964? Commented Mar 17, 2012 at 17:37
  • You could just multiply out the decimal and then divide it back in. i.e. mulitply 152.35964 by 10^n, convert, and then divide by base^n Commented Mar 17, 2012 at 17:41

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Without a clear indication of what the OP means, we can only guess
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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.