/** * Convert a string to long. * The input string is first be trimmed * and then it is parsed with traditional binary prefix. * * For example, * "-1230k" will be converted to -1230 * 1024 = -1259520; * "891g" will be converted to 891 * 1024^3 = 956703965184; * * @param s input string * @return a long value represented by the input string. */ public static long string2long(String s) { s = s.trim(); final int lastpos = s.length() - 1; final char lastchar = s.charAt(lastpos); if (Character.isDigit(lastchar)) return Long.parseLong(s); else { long prefix = TraditionalBinaryPrefix.valueOf(lastchar).value; long num = Long.parseLong(s.substring(0, lastpos)); if (num > (Long.MAX_VALUE/prefix) || num < (Long.MIN_VALUE/prefix)) { throw new IllegalArgumentException(s + " does not fit in a Long"); } return num * prefix; } } }
/** * @return The TraditionalBinaryPrefix object corresponding to the symbol. */ public static TraditionalBinaryPrefix valueOf(char symbol) { symbol = Character.toUpperCase(symbol); for(TraditionalBinaryPrefix prefix : TraditionalBinaryPrefix.values()) { if (symbol == prefix.symbol) { return prefix; } } throw new IllegalArgumentException("Unknown symbol '" + symbol + "'"); }
/** * Convert a string to long. * The input string is first be trimmed * and then it is parsed with traditional binary prefix. * * For example, * "-1230k" will be converted to -1230 * 1024 = -1259520; * "891g" will be converted to 891 * 1024^3 = 956703965184; * * @param s input string * @return a long value represented by the input string. */ public static long string2long(String s) { s = s.trim(); final int lastpos = s.length() - 1; final char lastchar = s.charAt(lastpos); if (Character.isDigit(lastchar)) return Long.parseLong(s); else { long prefix = TraditionalBinaryPrefix.valueOf(lastchar).value; long num = Long.parseLong(s.substring(0, lastpos)); if (num > (Long.MAX_VALUE/prefix) || num < (Long.MIN_VALUE/prefix)) { throw new IllegalArgumentException(s + " does not fit in a Long"); } return num * prefix; } } }
TraditionalBinaryPrefix(long value) { this.value = value; this.symbol = toString().charAt(0); }
TraditionalBinaryPrefix(long value) { this.value = value; this.symbol = toString().charAt(0); }
/** * @return The TraditionalBinaryPrefix object corresponding to the symbol. */ public static TraditionalBinaryPrefix valueOf(char symbol) { symbol = Character.toUpperCase(symbol); for(TraditionalBinaryPrefix prefix : TraditionalBinaryPrefix.values()) { if (symbol == prefix.symbol) { return prefix; } } throw new IllegalArgumentException("Unknown symbol '" + symbol + "'"); }