5

The base_convert() function doesn't seem to preserve the sign.

For example:

var_dump (base_convert ('-100', 10, 10));

The output of this is 100

Is there a way of converting bases without losing the sign?

GordonM
  • 31,179
  • 15
  • 87
  • 129

1 Answers1

6

I did not see a PHP standard function to do so, however you could write your own.

function signed_base_convert($number, $src_base, $dest_base)
{
    $sign = (intval($number, $src_base) >= 0 ? '' : '-');
    return $sign . base_convert($number, $src_base, $dest_base);
}

I do not have access to PHP at the moment to test this, but it should give you a good idea.

Brandon Horsley
  • 7,956
  • 1
  • 29
  • 28
  • I created an utility for dealing with base conversion between arbitrary numbers and bases, please have a look: https://github.com/thunderer/Numbase – Tomasz Kowalczyk Apr 24 '15 at 20:08