Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Generally I have no preference to paste such code but anyways, 100 lines how it's done (production code) I'd not advise using it but having some reference code it's nice (usually)</p> <pre><code>package t1; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; public class IntParser { final static byte[] digits = { '0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , 'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g' , 'h' , 'i' , 'j' , 'k' , 'l' , 'm' , 'n' , 'o' , 'p' , 'q' , 'r' , 's' , 't' , 'u' , 'v' , 'w' , 'x' , 'y' , 'z' }; static boolean isDigit(byte b) { return b&gt;='0' &amp;&amp; b&lt;='9'; } static int digit(byte b){ //negative = error int result = b-'0'; if (result&gt;9) result = -1; return result; } static NumberFormatException forInputString(ByteBuffer b){ byte[] bytes=new byte[b.remaining()]; b.get(bytes); try { return new NumberFormatException("bad integer: "+new String(bytes, "8859_1")); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } public static int parseInt(ByteBuffer b){ return parseInt(b, 10, b.position(), b.limit()); } public static int parseInt(ByteBuffer b, int radix, int i, int max) throws NumberFormatException{ int result = 0; boolean negative = false; int limit; int multmin; int digit; if (max &gt; i) { if (b.get(i) == '-') { negative = true; limit = Integer.MIN_VALUE; i++; } else { limit = -Integer.MAX_VALUE; } multmin = limit / radix; if (i &lt; max) { digit = digit(b.get(i++)); if (digit &lt; 0) { throw forInputString(b); } else { result = -digit; } } while (i &lt; max) { // Accumulating negatively avoids surprises near MAX_VALUE digit = digit(b.get(i++)); if (digit &lt; 0) { throw forInputString(b); } if (result &lt; multmin) { throw forInputString(b); } result *= radix; if (result &lt; limit + digit) { throw forInputString(b); } result -= digit; } } else { throw forInputString(b); } if (negative) { if (i &gt; b.position()+1) { return result; } else { /* Only got "-" */ throw forInputString(b); } } else { return -result; } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload