Muhammad Hewedy
Muhammad Hewedy

Reputation: 30056

A question in java.lang.Integer internal code

While looking in the code of the method:

Integer.toHexString

I found the following code :

public static String toHexString(int i) {
    return toUnsignedString(i, 4);
}

private static String toUnsignedString(int i, int shift) {
    char[] buf = new char[32];
    int charPos = 32;
    int radix = 1 << shift;
    int mask = radix - 1;
    do {
        buf[--charPos] = digits[i & mask];
        i >>>= shift;
    } while (i != 0);

    return new String(buf, charPos, (32 - charPos));
}

The question is, in toUnsignedString, why we create a char arr of 32 chars?

Upvotes: 4

Views: 233

Answers (3)

vinaynag
vinaynag

Reputation: 271

Because the max value for an int in Java is : 2^31 - 1

Upvotes: 1

Michael Borgwardt
Michael Borgwardt

Reputation: 346309

Because that method is also called by toBinaryString(), and an int is up to 32 digits in binary.

Upvotes: 2

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

32 characters is how much you need to represent an int in binary (base-2, shift of 1, used by toBinaryString).

It could be sized exactly, but I guess it has never made business sense to attempt that optimisation.

Upvotes: 9

Related Questions