Java – converts long to “byte array ed” text without heap allocation
•
Java
I want to convert the (positive) original long into byte []
For example, a simple method is: 123 = > "123" = > [49,50,51]
However, converting long to string heap - assigns a string, which I try to avoid for my GC free library I'd rather render it directly on a preallocated byte array
Therefore, my problem is how to convert directly from long to byte [] representation. If I use the string constructor call (for the above example), I give "123" For clarity, I'm not going to encode long as a binary byte [], but as text
thank you! ñ
Solution
This simple procedure:
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,51]
I have tested the current time in milliseconds and worked as expected:
long l = System.currentTimeMillis(); ... System.out.println(Arrays.toString(array));
Output:
1406485727149 [49,52,48,54,56,53,55,49,57]
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码