Android String to Hex String Convert hexStringToCommonString(String hexString)

Here you can find the source of hexStringToCommonString(String hexString)

Description

hex String To Common String

Parameter

Parameter Description
hexString a parameter

Declaration

public static String hexStringToCommonString(String hexString) 

Method Source Code

//package com.java2s;
import java.io.UnsupportedEncodingException;

import android.annotation.SuppressLint;

public class Main {

    public static String hexStringToCommonString(String hexString) {
        byte[] bytes = hexStringToBytes(hexString);
        try {/*from w w  w  . j  a v  a 2s .  c om*/
            return new String(bytes, "gbk");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return new String(bytes);
        }
    }

    /**
     * Convert hex string to byte[]
     * 
     * @param hexString
     *            the hex string
     * @return byte[]
     */
    @SuppressLint("DefaultLocale")
    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int byteArrayLength = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();

        byte[] d = new byte[byteArrayLength];
        for (int i = 0; i < byteArrayLength; 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);
    }
}

Related

  1. toHex(String txt)
  2. toHex(byte[] buf)
  3. toHexString(String str)
  4. hexStr2Str(String hexStr)
  5. toHex(String txt)
  6. toHex(String txt)
  7. parseHexStr2Byte(String hexStr)
  8. stringToHex(String string)