001/** 002 * 003 * Copyright (c) 2014, the Railo Company Ltd. All rights reserved. 004 * 005 * This library is free software; you can redistribute it and/or 006 * modify it under the terms of the GNU Lesser General Public 007 * License as published by the Free Software Foundation; either 008 * version 2.1 of the License, or (at your option) any later version. 009 * 010 * This library is distributed in the hope that it will be useful, 011 * but WITHOUT ANY WARRANTY; without even the implied warranty of 012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 013 * Lesser General Public License for more details. 014 * 015 * You should have received a copy of the GNU Lesser General Public 016 * License along with this library. If not, see <http://www.gnu.org/licenses/>. 017 * 018 **/ 019package lucee.commons.lang; 020 021import lucee.runtime.exp.ExpressionException; 022 023public class NumberUtil { 024 public static int hexToInt(String s, int defaultValue) { 025 try { 026 return hexToInt(s); 027 } catch (ExpressionException e) { 028 return defaultValue; 029 } 030 } 031 public static int hexToInt(String s) throws ExpressionException { 032 int[] n = new int[s.length()]; 033 char c; 034 int sum = 0; 035 int koef = 1; 036 for(int i=n.length-1; i>=0; i--) { 037 c = s.charAt(i); 038 039 if(!((c>='0' && c<='9') || (c>='a' && c<='f'))) { 040 throw new ExpressionException("invalid hex constant ["+c+"], hex constants are [0-9,a-f]"); 041 } 042 043 //System.out.println(c); 044 switch (c) { 045 case 48: 046 n[i] = 0; 047 break; 048 case 49: 049 n[i] = 1; 050 break; 051 case 50: 052 n[i] = 2; 053 break; 054 case 51: 055 n[i] = 3; 056 break; 057 case 52: 058 n[i] = 4; 059 break; 060 case 53: 061 n[i] = 5; 062 break; 063 case 54: 064 n[i] = 6; 065 break; 066 case 55: 067 n[i] = 7; 068 break; 069 case 56: 070 n[i] = 8; 071 break; 072 case 57: 073 n[i] = 9; 074 break; 075 case 97: 076 n[i] = 10; 077 break; 078 case 98: 079 n[i] = 11; 080 break; 081 case 99: 082 n[i] = 12; 083 break; 084 case 100: 085 n[i] = 13; 086 break; 087 case 101: 088 n[i] = 14; 089 break; 090 case 102: 091 n[i] = 15; 092 break; 093 } 094 095 sum = sum + n[i]*koef; 096 koef=koef*16; 097 } 098 return sum; 099 } 100 public static byte[] longToByteArray(long l) { 101 byte[] ba=new byte[8]; 102 for(int i=0; i<64; i+=8) { 103 ba[i>>3] = new Long((l&(255L<<i))>>i).byteValue(); 104 } 105 return ba; 106 } 107 108 public static long byteArrayToLong(byte[] ba){ 109 long l=0; 110 for(int i=0; (i<8)&&(i<8); i++) { 111 l |= (((long)ba[i])<<(i<<3))&(255L<<(i<<3)); 112 } 113 return l; 114 } 115 public static int randomRange(int min, int max) { 116 return min + (int)(Math.random() * ((max - min) + 1)); 117 } 118}