fazlurr
3/14/2015 - 11:41 AM

Java Data Converter

Java Data Converter

package com.kurniadi.asep.secmessage.encryption;

import java.math.BigInteger;

/**
 * Created by Asep on 14/03/2015.
 * Data convert utility
 */
public class DataUtils {
    final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();

    /**
     * From : http://stackoverflow.com/a/9855338
     * @param bytes bytes
     * @return hexadecimal string
     */
    public static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        for ( int j = 0; j < bytes.length; j++ ) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }

    /**
     * From : http://stackoverflow.com/a/943963
     * @param bytes bytes
     * @return hexadecimal string
     */
    public static String bytesToHex2(byte[] bytes) {
        BigInteger bi = new BigInteger(1, bytes);
        return String.format("%0" + (bytes.length << 1) + "X", bi);
    }

    /**
     * From : http://stackoverflow.com/a/140861
     * @param s string
     * @return byte array
     */
    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i+1), 16));
        }
        return data;
    }
}