简体   繁体   中英

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?

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.

因为toBinaryString()也调用了该方法,并且int二进制数最多为32位。

因为Java中int的最大值是:2 ^ 31 - 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM