Converting Hexadecimal String to Decimal Integer

后端 未结 14 1985
感动是毒
感动是毒 2020-12-09 16:02

I wrote some code to convert my hexadecimal display string to decimal integer. However, when input is something like 100a or 625b( something with letter) I got an error like

14条回答
  •  误落风尘
    2020-12-09 16:37

      public static int hex2decimal(String s) {
                 String digits = "0123456789ABCDEF";
                 s = s.toUpperCase();
                 int val = 0;
                 for (int i = 0; i < s.length(); i++) {
                     char c = s.charAt(i);
                     int d = digits.indexOf(c);
                     val = 16*val + d;
                 }
                 return val;
             }
    

    That's the most efficient and elegant solution I have found over the internet. Some of the others solutions provided here didn't always work for me.

提交回复
热议问题