001package ca.bc.webarts; 002public class TestHexInt 003{ 004 005 /** 006 * main entry to this app. 007 **/ 008 public static void main(String args[]) 009 { 010 String hexStr = "fffffcef"; 011 TestHexInt instance = new TestHexInt(); 012 if (args.length>0) 013 { 014 hexStr = args[0]; 015 } 016 System.out.println("Testing..."); 017 System.out.println("hexStr "+hexStr+" = "+instance.parseIntFromHex(hexStr)); 018 } 019 020 021 022 /** Parse a string holding a hex value into a SIGNED int AND work Around a Java bug (id= 023 * <a href="http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4215269">4215269</a>) 024 * int is signed: -2^31 to +2^31-1 but the above mentioned bug throughs an exception for 0xFFFFFFFF or +2^31-1 025 * so that value (2147483647) is used as the error value and 026 * the biggest value this method returns is 0xfffffffe or 2147483646 027 * 028 * @param hexstr is a string representing an int value Must be less than 9 chars in length (ie max int size) 029 * @return the converted value -2^31 to +2^31-2 (or 2147483647 if it caused an error) 030 **/ 031 public int parseIntFromHex(String hexStr) 032 { 033 int retVal = 2147483647; 034 if(hexStr.startsWith("0x") || hexStr.startsWith("0X")) 035 hexStr = hexStr.substring(2); 036 037 // work around for JAVA BUG: http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4215269 038 if(hexStr.equalsIgnoreCase("ffffffff")) 039 hexStr = "fffffffe"; 040 041 try 042 { 043 //fffffcef 044 retVal = Integer.parseInt( hexStr, 16); // this Parses the string argument as a signed integer in the radix 045 // specified by the second argument. The characters in the string must all be digits of 046 // the specified radix (as determined by whether Character.digit(char, int) returns 047 // a nonnegative value), except that the first character may be an ASCII minus 048 // sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') 049 // to indicate a positive value. The resulting integer value is returned. 050 } 051 catch (Exception ex) 052 { 053 ex.printStackTrace(); 054 System.out.println("non-fatal error: can't convert hex ("+hexStr+") to a signed int"); 055 056 } 057 058 return retVal; 059 } 060 061 062}