简体   繁体   English

java.lang.Integer内部代码中的一个问题

[英]A question in java.lang.Integer internal code

While looking in the code of the method: 在查看方法的代码时:

Integer.toHexString 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? 问题是,在toUnsignedString中,为什么我们创建一个包含32个字符的char arr?

32 characters is how much you need to represent an int in binary (base-2, shift of 1, used by toBinaryString ). 32个字符是你需要多少来表示二进制中的int (base-2, shift为1,由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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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