Java Digit From toDigit(final char ch, final int index)

Here you can find the source of toDigit(final char ch, final int index)

Description

to Digit

License

Open Source License

Parameter

Parameter Description
ch a parameter
index a parameter

Exception

Parameter Description
RuntimeException an exception

Declaration

private static int toDigit(final char ch, final int index) throws RuntimeException 

Method Source Code

//package com.java2s;

public class Main {
    private static final char CH_ZERO = '0';
    private static final char CH_LCASE_A = 'a';
    private static final short CH_LCASE_A_M10 = 87;
    private static final short CH_UCASE_A_M10 = 55;
    private static final IllegalArgumentException ILLEGAL_CHARACTER = new IllegalArgumentException(
            "must [0-9],[a-z],[A-Z]");

    /**// w  w w .  j a v a  2 s .  c  o m
     * 
     * @param ch
     * @param index
     * @return
     * @throws RuntimeException
     */
    private static int toDigit(final char ch, final int index) throws RuntimeException {
        final int digit = fastDigit(ch);
        if (digit == -1) {
            throw new RuntimeException("Illegal hexadecimal charcter " + ch + " at index " + index);
        }
        return digit;
    }

    /**
     * 
     * @param c
     * @see Character#digit(char, int)
     * @return
     */
    public static int fastDigit(final char c) {
        if (c >= CH_ZERO && c <= '9') {
            return (c - CH_ZERO);
        }
        if (c >= CH_LCASE_A && c <= 'f') {
            return (c - CH_LCASE_A_M10);
        }

        if (c >= 'A' && c <= 'F') {
            return (c - CH_UCASE_A_M10);
        }
        throw ILLEGAL_CHARACTER;
    }

    /**
     * 
     * @param c
     * @see Character#digit(int, int)
     * @return
     */
    public static int fastDigit(final int c) {
        if (c >= CH_ZERO && c <= '9') {
            return (c - CH_ZERO);
        }
        if (c >= CH_LCASE_A && c <= 'f') {
            return (c - CH_LCASE_A_M10);
        }

        if (c >= 'A' && c <= 'F') {
            return (c - CH_UCASE_A_M10);
        }
        throw ILLEGAL_CHARACTER;
    }
}

Related

  1. toDigit(char c)
  2. toDigit(char ch)
  3. toDigit(char ch, int index)
  4. toDigit(final boolean bit)
  5. toDigit(final char ch, final int index)
  6. toDigit(final int value)
  7. toDigit(int c)
  8. toDigit(int i)