4

Is there any built-in libraries (or any good 3rd party code) that support converting a number from any arbitrary base A to another base B?

Thanks,

One Two Three
  • 22,327
  • 24
  • 73
  • 114

1 Answers1

8

Um, Integer.toString(int, base) and Integer.parseInt(String, base)...?

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • Uhm, I'd rather not go thru an intermediate state. (.parseInt(...) doesn't look very fast) (This is my school graduation project where performance is quite critical) – One Two Three May 22 '12 at 17:18
  • How are you getting the inputs, then, if not as a `String` or read from a file or from the console? The intermediate state is an `int`, and you're not going to get faster than that. – Louis Wasserman May 22 '12 at 17:22
  • The input could either be a String or an Integer/Long – One Two Three May 22 '12 at 17:23
  • Sure. So if your input is an `int`, then the _output_ is going to be a `String`, in which case you use `Integer.toString`. In any event, for general base conversions, I don't think it's even possible to find an implementation that's going to be faster by more than one or two percentage points. Stick to the way it's supposed to be done. If I cared about performance, this is still the way I'd do it. – Louis Wasserman May 22 '12 at 17:24
  • Oh ok. But I'm still hoping 'somehwere' out there, there is an API that would be capable of converting directly a number from base A to base B. :) – One Two Three May 22 '12 at 17:32
  • 1
    A number by itself doesn't have a base (if any: it would be base 2 as integers are stored in binary form in your computer). The only area where base has any meaning is for input or output when they are both a String. – Mark Rotteveel May 22 '12 at 17:34
  • Indeed. "Base conversion" doesn't make any _sense_ unless you're converting a `String` to an `int` or vice versa, or from a `String` to another `String` -- in which case going via an `int` is still the fastest way to do it. – Louis Wasserman May 22 '12 at 17:36