rainman
rainman

Reputation: 2659

How to convert a negative number to base in Java

I have a negative integer n does anyone know can I convert to a base P in Java ?

Let's say n= -31246 how to convert it to base 4 ?

Upvotes: 1

Views: 229

Answers (2)

Jerin Joseph
Jerin Joseph

Reputation: 1097

You can use the Integer.toString,

Integer.toString(i, 4);

From the documentation,

public static String toString(int i, int radix)

Returns a string representation of the first argument in the radix specified by the second argument. If the radix is smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX, then the radix 10 is used instead.

If the first argument is negative, the first element of the result is the ASCII minus character '-' ('\u002D'). If the first argument is not negative, no sign character appears in the result.

The remaining characters of the result represent the magnitude of the first argument. If the magnitude is zero, it is represented by a single zero character '0' ('\u0030'); otherwise, the first character of the representation of the magnitude will not be the zero character. The following ASCII characters are used as digits:

Upvotes: 1

user4910279
user4910279

Reputation:

Try this.

Integer.toString(-31246, 4)

Upvotes: 0

Related Questions