Converting Hexadecimal String to Decimal Integer

后端 未结 14 1953
感动是毒
感动是毒 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:41

    You could take advantage of ASCII value for each letter and take off 55, easy and fast:

    int asciiOffset = 55;
    char hex = Character.toUpperCase('A');  // Only A-F uppercase
    int val = hex - asciiOffset;
    System.out.println("hexadecimal:" + hex);
    System.out.println("decimal:" + val);
    

    Output:
    hexadecimal:A
    decimal:10

提交回复
热议问题