1 package org.apache.lucene.document; 2 3 18 19 20 35 public class NumberTools { 36 37 private static final int RADIX = 36; 38 39 private static final char NEGATIVE_PREFIX = '-'; 40 41 private static final char POSITIVE_PREFIX = '0'; 43 44 48 public static final String MIN_STRING_VALUE = NEGATIVE_PREFIX 49 + "0000000000000"; 50 51 54 public static final String MAX_STRING_VALUE = POSITIVE_PREFIX 55 + "1y2p0ij32e8e7"; 56 57 60 public static final int STR_SIZE = MIN_STRING_VALUE.length(); 61 62 65 public static String longToString(long l) { 66 67 if (l == Long.MIN_VALUE) { 68 return MIN_STRING_VALUE; 70 } 71 72 StringBuffer buf = new StringBuffer (STR_SIZE); 73 74 if (l < 0) { 75 buf.append(NEGATIVE_PREFIX); 76 l = Long.MAX_VALUE + l + 1; 77 } else { 78 buf.append(POSITIVE_PREFIX); 79 } 80 String num = Long.toString(l, RADIX); 81 82 int padLen = STR_SIZE - num.length() - buf.length(); 83 while (padLen-- > 0) { 84 buf.append('0'); 85 } 86 buf.append(num); 87 88 return buf.toString(); 89 } 90 91 101 public static long stringToLong(String str) { 102 if (str == null) { 103 throw new NullPointerException ("string cannot be null"); 104 } 105 if (str.length() != STR_SIZE) { 106 throw new NumberFormatException ("string is the wrong size"); 107 } 108 109 if (str.equals(MIN_STRING_VALUE)) { 110 return Long.MIN_VALUE; 111 } 112 113 char prefix = str.charAt(0); 114 long l = Long.parseLong(str.substring(1), RADIX); 115 116 if (prefix == POSITIVE_PREFIX) { 117 } else if (prefix == NEGATIVE_PREFIX) { 119 l = l - Long.MAX_VALUE - 1; 120 } else { 121 throw new NumberFormatException ( 122 "string does not begin with the correct prefix"); 123 } 124 125 return l; 126 } 127 } | Popular Tags |