0

I'd like to convert integers from decimal base to quaternal base. What is the more concise way to do it ?

// From 4-base to decimal int d = Integer.parseInt("10", 4); // 5 // From decimal to decimal string String b10 = String.valueOf(d); // "5" // From decimal to 4-base string ? String b4 = yourMagicFunction(d, 4); // "10" 
1
  • 1
    To convert an integer from one base to another base, you can use Integer.toString(Integer.parseInt(number, base1), base2); Commented Apr 1, 2013 at 2:12

2 Answers 2

4

Are you just looking for Integer.toString(int, int)?

String b4 = Integer.toString(5, 4); // b4 = "11" 

(Note the 11 rather than 10... parsing "10" base 4 gives 4, not 5.)

It's not clear what you're looking for beyond Integer.parseInt(String, int) and Integer.toString(int, int)...

Sign up to request clarification or add additional context in comments.

2 Comments

+1 : Thanks. Yes, it was simple but had a long time without Java :p
Oh my god, but you are Jon Skeet !
1
Integer.toString(d, 4); 

The Integer.toString method can convert to any radix between Character.MIN_RADIX and Character.MAX_RADIX.

However, Java ints (such as d) are stored as binary internally, not decimal.

7 Comments

What do you mean by "the source is binary"?
@JonSkeet, just that d is a two's complement binary integer.
It's still not really clear what you mean to me. An integer is an integer. It's only "decimal" or "binary" after formatting.
@Jon, JLS 4.2 requires that it's a "signed two's-complement integer" in memory, which also implies it's binary. The OP talks about converting from "decimal to decimal string", implying that the internal representation is decimal. I just wanted to indicate that the actual internal representation is binary.
The internal representation isn't particularly relevant, IMO - it's just an integer. I thought the question made it fairly clear he was talking about string representations.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.