Q:

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

A:

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]

A:

To write it without using a byte[] or using Math.pow and Math.log which are pretty expensive you can do the following. 
public static void toStream(OutputStream os, long l) throws IOException {
    toStream0(os, l / 10);
    os.write((int) ('0' + l % 10));
}

private static void toStream0(OutputStream os, long l) throws IOException {
    if (l == 0) return;
    toStream0(os, l / 10);
    os.write((int) ('0' + l % 10));
}

toStream(System.out, System.currentTimeMillis());

prints
1406486588664

If you are writing to a ByteBuffer, use put( or a StringBuilder use append((char)
You might consider larger bases to make the number smaller. 
base 36: hy4p6ugr
base 16: 147791288bb
base 10: 1406485563579

