Determine if given string is a valid Hex representation of an ASCII character (eg. - Java java.lang

Java examples for java.lang:Hex

Description

Determine if given string is a valid Hex representation of an ASCII character (eg.

Demo Code

/*******************************************************************************
 * Copyright (c) 2004, 2008 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * //from ww w  .  j  av a2s  . co m
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String possible = "java2s.com";
        System.out.println(isValid(possible));
    }

    /**
     * Determine if given string is a valid Hex representation of an ASCII
     * character (eg. 2F -> /)
     * 
     * @param possible
     * @return
     */
    private static boolean isValid(String possible) {
        boolean result = false;
        if (possible.length() == 2) {
            char c1 = possible.charAt(0);
            char c2 = possible.charAt(1);
            // 1st character must be a digit
            if (Character.isDigit(c1)) {
                // 2nd character must be digit or upper case letter A-F
                if (Character.isDigit(c2)) {
                    result = true;
                } else if (Character.isUpperCase(c2)
                        && (c2 == 'A' || c2 == 'B' || c2 == 'C'
                                || c2 == 'D' || c2 == 'E' || c2 == 'F')) {
                    result = true;
                }
            }
        }
        return result;
    }
}

Related Tutorials