NT_ NT_ - 4 months ago 6
Java Question

Convert long to "byte-array-ed" text, without heap allocations

I would like to convert a (positive) primitive long to a

byte[]
in its textual form, in Java.

For example an easy way would be:
123 => "123" => [49, 50, 51]


However converting long to
String
heap-allocates a
String
and I'm trying to avoid this for my GC-free library. I would rather render this directly on a pre-allocated byte array.

Hence, my question is how do I go directly from long to a
byte[]
representation, which if I call with a String constructor would (for the above example) given me "123". To clarify, I'm not looking to encode the long as a
byte[]
in binary form, but rather textual form.

Thanks!
N

Answer

This simple program:

long l = 123;
int size = (int)(Math.log10(l)+1);
byte[] array = new byte[size];
for (int i = 0; i < size; i++) {
    long temp = (long) Math.pow(10, size - i - 1);
    array[i] = (byte) ((l / temp) + 48);
    l = l % temp;
}
System.out.println(Arrays.toString(array)); // [49, 50, 51]

I have tested it for current time in milli-seconds as well and working as expected:

long l = System.currentTimeMillis();
...
System.out.println(Arrays.toString(array));

output:

1406485727149
[49, 52, 48, 54, 52, 56, 53, 55, 50, 55, 49, 52, 57]
Comments