Question in java.lang.Integer internal code

When viewing the method code:

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, do we create a char arr of 32 characters in toUnsignedString?

+4
source share
3 answers

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

It can be accurately calculated, but I believe that it never made sense to attempt this optimization.

+9
source

Since this method is also called toBinaryString() , and int is up to 32 digits in binary format.

+2
source

Since the maximum value for int in Java is: 2 ^ 31 - 1

+1
source

Source: https://habr.com/ru/post/1308375/


All Articles