/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cz.karry.dop.nbmodule;

/**
 *
 * @author karry
 */
public class Utils {
    
    public static String intToHex(int value, int width){
        String res = Integer.toHexString(value).toUpperCase();
        while (res.length() < width){
            res = "0"+res;
        }
        return res;
    }

    public static String intToHex(int value){
        return Integer.toHexString(value).toUpperCase();
    }

    public static int hexToInt(String value) throws Exception {
        value = value.toUpperCase();
        int result = 0;
        int exponent = 1;
        for (int i=1; i<=value.length(); i++){
            char ch = value.charAt(value.length()-i);
            
            switch (ch){
                case '0': result += 0  * exponent; break;
                case '1': result += 1  * exponent; break;
                case '2': result += 2  * exponent; break;
                case '3': result += 3  * exponent; break;
                case '4': result += 4  * exponent; break;
                case '5': result += 5  * exponent; break;
                case '6': result += 6  * exponent; break;
                case '7': result += 7  * exponent; break;
                case '8': result += 8  * exponent; break;
                case '9': result += 9  * exponent; break;
                case 'A': result += 10 * exponent; break;
                case 'B': result += 11 * exponent; break;
                case 'C': result += 12 * exponent; break;
                case 'D': result += 13 * exponent; break;
                case 'E': result += 14 * exponent; break;
                case 'F': result += 15 * exponent; break;
                default: throw new Exception("Hexadecimal string \""+value+"\" is not convertable to integer.");
            }
            exponent *= 16;
        }
        return result;
    }
}
