Java Char to Nibble charToNibble(char c)

Here you can find the source of charToNibble(char c)

Description

convert a single char to corresponding nibble using a precalculated array.

License

Open Source License

Parameter

Parameter Description
c char to convert. must be 0-9 a-f A-F, no spaces, plus or minus signs.

Exception

Parameter Description
IllegalArgumentException on invalid c.

Return

corresponding integer 0..15

Declaration

private static int charToNibble(char c) 

Method Source Code

//package com.java2s;
/* //  www .  j  a  va 2  s . c  om
 * @(#)TestHex.java 
 * 
 * Summary: Demonstrate how to handle hex strings. 
 * 
 * Copyright: (c) 2009-2010 Roedy Green, Canadian Mind Products, http://mindprod.com 
 * 
 * Licence: This software may be copied and used freely for any purpose but military. 
 *          http://mindprod.com/contact/nonmil.html 
 * 
 * Requires: JDK 1.6+ 
 * 
 * Created with: IntelliJ IDEA IDE. 
 * 
 * Version History: 
 *  1.0 2009-06-05 - initial version. 
 */

public class Main {
    /** 
     * precomputed translate table for chars 0..'f' 
     */
    private static byte[] correspondingNibble = new byte['f' + 1];

    /** 
     * convert  a single char to corresponding nibble using a precalculated array. 
     * Based on code by: 
     * Brian Marquis 
     * Orion Group Software Engineers http://www.ogse.com 
     * 
     * @param c char to convert. must be 0-9 a-f A-F, no 
     *          spaces, plus or minus signs. 
     * 
     * @return corresponding integer  0..15 
     * @throws IllegalArgumentException on invalid c. 
     */
    private static int charToNibble(char c) {
        if (c > 'f') {
            throw new IllegalArgumentException("Invalid hex character: " + c);
        }
        int nibble = correspondingNibble[c];
        if (nibble < 0) {
            throw new IllegalArgumentException("Invalid hex character: " + c);
        }
        return nibble;
    }
}

Related

  1. charToNibble(char c)
  2. charToNibble(char c)
  3. charToNibble(char c)