More fast int to string (in decimal base) implementation for Java. It uses external bytes buffer an it can be useful if need write number to stream as fast as possible.
1 package cy6ergn0m;
2
3
4
5 @author
6
7 public class NumbersChars {
8
9 final static int[] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
10 99999999, 999999999, Integer.MAX_VALUE
11 };
12
13 final static byte[] digits = {
14 '0', '1', '2', '3', '4', '5',
15 '6', '7', '8', '9', 'a', 'b',
16 'c', 'd', 'e', 'f', 'g', 'h',
17 'i', 'j', 'k', 'l', 'm', 'n',
18 'o', 'p', 'q', 'r', 's', 't',
19 'u', 'v', 'w', 'x', 'y', 'z'
20 };
21 final static byte[] DigitTens = {
22 '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
23 '1', '1', '1', '1', '1', '1', '1', '1', '1', '1',
24 '2', '2', '2', '2', '2', '2', '2', '2', '2', '2',
25 '3', '3', '3', '3', '3', '3', '3', '3', '3', '3',
26 '4', '4', '4', '4', '4', '4', '4', '4', '4', '4',
27 '5', '5', '5', '5', '5', '5', '5', '5', '5', '5',
28 '6', '6', '6', '6', '6', '6', '6', '6', '6', '6',
29 '7', '7', '7', '7', '7', '7', '7', '7', '7', '7',
30 '8', '8', '8', '8', '8', '8', '8', '8', '8', '8',
31 '9', '9', '9', '9', '9', '9', '9', '9', '9', '9',
32 };
33 final static byte[] DigitOnes = {
34 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
35 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
36 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
37 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
38 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
39 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
40 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
41 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
42 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
43 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
44 };
45
46
47 static int stringSize ( int x ) {
48 for ( int i = 0;; i++ )
49 if ( x <= sizeTable[i] )
50 return i + 1;
51 }
52
53 static void getChars ( int i, int index, byte[] buf ) {
54 int q, r;
55 int charPos = index;
56 byte sign = 0;
57
58 if ( i < 0 ) {
59 sign = '-';
60 i = -i;
61 }
62
63
64 while ( i >= 65536 ) {
65 q = i / 100;
66
67 r = i - ( ( q << 6 ) + ( q << 5 ) + ( q << 2 ) );
68 i = q;
69 buf[--charPos] = DigitOnes[r];
70 buf[--charPos] = DigitTens[r];
71 }
72
73
74
75 for (;;) {
76 q = ( i * 52429 ) >>> ( 16 + 3 );
77 r = i - ( ( q << 3 ) + ( q << 1 ) );
78
79 buf[--charPos] = digits[r];
80 i = q;
81 if ( i == 0 )
82 break;
83 }
84 if ( sign != 0 )
85 buf[--charPos] = sign;
86 }
87
88 public static int i2s ( int i, byte[] buffer ) {
89 int size = ( i < 0 ) ? stringSize( -i ) + 1 : stringSize( i );
90 if ( size > buffer.length )
91 throw new IllegalArgumentException( "buffer too small" );
92 getChars( i, size, buffer );
93 return size;
94 }
95
96 }
97
98
Комментариев нет:
Отправить комментарий