android, kotlin convert Long to hex string

Viewed 1824

converting java code to kotlin, seems kotlin has Long.toString(16), but not sure if it is better to keep calling to the java's, any suggestion which one is better?

java.lang.Long.toHexString(theLong)

which calls:

which:

public static String toHexString(long i) {
        return toUnsignedString0(i, 4);
    }

static String toUnsignedString0(long val, int shift) {
        // assert shift > 0 && shift <=5 : "Illegal shift value";
        int mag = Long.SIZE - Long.numberOfLeadingZeros(val);
        int chars = Math.max(((mag + (shift - 1)) / shift), 1);
        char[] buf = new char[chars];

        formatUnsignedLong(val, shift, buf, 0, chars);
        // Android-changed: Use regular constructor instead of one which takes over "buf".
        // return new String(buf, true);
        return new String(buf);
    }

     static int formatUnsignedLong(long val, int shift, char[] buf, int offset, int len) {
        int charPos = len;
        int radix = 1 << shift;
        int mask = radix - 1;
        do {
            buf[offset + --charPos] = Integer.digits[((int) val) & mask];
            val >>>= shift;
        } while (val != 0 && charPos > 0);

        return charPos;
    }

or kotlin

theLong.toString(16)

which calls

public actual inline fun Long.toString(radix: Int): String = java.lang.Long.toString(this, checkRadix(radix))

which:
public static String toString(long i, int radix) {
        if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
            radix = 10;
        if (radix == 10)
            return toString(i);
        char[] buf = new char[65];
        int charPos = 64;
        boolean negative = (i < 0);

        if (!negative) {
            i = -i;
        }

        while (i <= -radix) {
            buf[charPos--] = Integer.digits[(int)(-(i % radix))];
            i = i / radix;
        }
        buf[charPos] = Integer.digits[(int)(-i)];

        if (negative) {
            buf[--charPos] = '-';
        }

        return new String(buf, charPos, (65 - charPos));
    }
1 Answers
  • kotlin.Long.toString(radix: Int) is signed, which means it will return a string with a negative sign for negative values (or values over 2^63 - 1 if we think in terms of unsigned numbers).

  • Long.toHexString(long i) is unsigned, you will never see a negative sign prefix. The method is also optimized for powers of two, using shift operators instead of division, so performance might be slightly better. However this should literally be the last of your concerns.

So if you don't plan on having to format values over 2^63 - 1, use Kotlin's function, otherwise use Java's. A third option would be to use ULong.toString if you want to avoid using Java methods.

Related