Java: parse int value from a char

后端 未结 7 1163
借酒劲吻你
借酒劲吻你 2020-11-22 16:10

I just want to know if there\'s a better solution to parse a number from a character in a string (assuming that we know that the character at index n is a number).



        
相关标签:
7条回答
  • 2020-11-22 16:54

    Using binary AND with 0b1111:

    String element = "el5";
    
    char c = element.charAt(2);
    
    System.out.println(c & 0b1111); // => '5' & 0b1111 => 0b0011_0101 & 0b0000_1111 => 5
    
    // '0' & 0b1111 => 0b0011_0000 & 0b0000_1111 => 0
    // '1' & 0b1111 => 0b0011_0001 & 0b0000_1111 => 1
    // '2' & 0b1111 => 0b0011_0010 & 0b0000_1111 => 2
    // '3' & 0b1111 => 0b0011_0011 & 0b0000_1111 => 3
    // '4' & 0b1111 => 0b0011_0100 & 0b0000_1111 => 4
    // '5' & 0b1111 => 0b0011_0101 & 0b0000_1111 => 5
    // '6' & 0b1111 => 0b0011_0110 & 0b0000_1111 => 6
    // '7' & 0b1111 => 0b0011_0111 & 0b0000_1111 => 7
    // '8' & 0b1111 => 0b0011_1000 & 0b0000_1111 => 8
    // '9' & 0b1111 => 0b0011_1001 & 0b0000_1111 => 9
    
    0 讨论(0)
提交回复
热议问题