@@ -36,54 +36,11 @@ public class Base58 {
3636 private static final String ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" ;
3737 private static final BigInteger BASE = BigInteger .valueOf (58 );
3838
39- public static String encode (byte [] input ) {
40- // TODO: This could be a lot more efficient.
41- BigInteger bi = new BigInteger (1 , input );
42- StringBuffer s = new StringBuffer ();
43- while (bi .compareTo (BASE ) >= 0 ) {
44- BigInteger mod = bi .mod (BASE );
45- s .insert (0 , ALPHABET .charAt (mod .intValue ()));
46- bi = bi .subtract (mod ).divide (BASE );
47- }
48- s .insert (0 , ALPHABET .charAt (bi .intValue ()));
49- // Convert leading zeros too.
50- for (byte anInput : input ) {
51- if (anInput == 0 )
52- s .insert (0 , ALPHABET .charAt (0 ));
53- else
54- break ;
55- }
56- return s .toString ();
39+ public static String encode (final byte [] input ) {
40+ return BaseN .encode (ALPHABET , BASE , input );
5741 }
5842
59- public static byte [] decode (String input ) {
60- byte [] bytes = decodeToBigInteger (input ).toByteArray ();
61- // We may have got one more byte than we wanted, if the high bit of the next-to-last byte was not zero. This
62- // is because BigIntegers are represented with twos-compliment notation, thus if the high bit of the last
63- // byte happens to be 1 another 8 zero bits will be added to ensure the number parses as positive. Detect
64- // that case here and chop it off.
65- boolean stripSignByte = bytes .length > 1 && bytes [0 ] == 0 && bytes [1 ] < 0 ;
66- // Count the leading zeros, if any.
67- int leadingZeros = 0 ;
68- for (int i = 0 ; input .charAt (i ) == ALPHABET .charAt (0 ); i ++) {
69- leadingZeros ++;
70- }
71- // Now cut/pad correctly. Java 6 has a convenience for this, but Android can't use it.
72- byte [] tmp = new byte [bytes .length - (stripSignByte ? 1 : 0 ) + leadingZeros ];
73- System .arraycopy (bytes , stripSignByte ? 1 : 0 , tmp , leadingZeros , tmp .length - leadingZeros );
74- return tmp ;
75- }
76-
77- public static BigInteger decodeToBigInteger (String input ) {
78- BigInteger bi = BigInteger .valueOf (0 );
79- // Work backwards through the string.
80- for (int i = input .length () - 1 ; i >= 0 ; i --) {
81- int alphaIndex = ALPHABET .indexOf (input .charAt (i ));
82- if (alphaIndex == -1 ) {
83- throw new IllegalStateException ("Illegal character " + input .charAt (i ) + " at " + i );
84- }
85- bi = bi .add (BigInteger .valueOf (alphaIndex ).multiply (BASE .pow (input .length () - 1 - i )));
86- }
87- return bi ;
43+ public static byte [] decode (final String input ) {
44+ return BaseN .decode (ALPHABET , BASE , input );
8845 }
8946}
0 commit comments