Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

public class Main {
    /****
     * 
     * @param deci
     * @return
     */
    public static byte[] decimalToHex2Bytes(int deci) {
        String hexStr = Integer.toHexString(deci);
        if (hexStr.length() == 3) {
            hexStr = "0" + hexStr;
        } else if (hexStr.length() == 2) {
            hexStr = "00" + hexStr;
        } else if (hexStr.length() == 1) {
            hexStr = "000" + hexStr;
        }
        return hexStringToBytes(hexStr);
    }

    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    /**
     * Convert char to byte
     * 
     * @param c
     *            char
     * @return byte
     */
    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }
}