Tom Stambaugh
Tom Stambaugh

Reputation: 1039

PHP inverse function for base_convert?

I have to do arithmetic with some ternary (base 3) numbers. I know I can use base_convert to get from a ternary string ("2001022210") to an integer. Is there an existing function to do the inverse?

I want "some_function" such that:

$someInteger = base_convert("2001022210", 10, 3);
some_function($someInteger);

answers "2001022210". I'm happy to provide extra arguments ...

some_function($someInteger, 3);
some_function($someInteger, 3, 10);

I know I can code this myself, but I'm hoping it's already there.

Upvotes: 0

Views: 1476

Answers (3)

tim
tim

Reputation: 3359

Tom. Please head over to http://php.net/ when you use php functions to see what they actually do. Reading and understanding a languages API is a general key for writing good code.

string base_convert ( string $number , int $frombase , int $tobase )

Returns a string containing number represented in base tobase. The base in which number is given is specified in frombase. Both frombase and tobase have to be between 2 and 36, inclusive. Digits in numbers with a base higher than 10 will be represented with the letters a-z, with a meaning 10, b meaning 11 and z meaning 35.

Now let $number be the number you want to convert:

  • If you want to convert it from ternary to decimal you use base_convert($number, 3, 10);
  • If you want to convert it from decimal to ternary you use base_convert($number, 10, 3);

Upvotes: 1

anon
anon

Reputation:

Yes, this can be done with base_convert():

As the PHP Manual says:

base_convert — Convert a number between arbitrary bases

So, the following would work:

base_convert($someinteger, 3, 10);

As a function:

function some_func($someinteger) {
    return base_convert($someinteger, 3, 10);
}

Upvotes: 0

Ben Kane
Ben Kane

Reputation: 10060

$someInteger is now in base 3... so just do $base10Int = base_convert($someInteger, 3, 10); to get it back.

Upvotes: 4

Related Questions