Here you can find the source of stringToHexByte(String str)
Parameter | Description |
---|---|
str | a parameter |
public static byte[] stringToHexByte(String str)
//package com.java2s; import java.io.UnsupportedEncodingException; import android.annotation.SuppressLint; public class Main { public static byte[] stringToHexByte(String str) { String hexString = bytesToHexString(str.getBytes()); return hexStringToBytes(hexString); }/* w w w. j av a 2s . c o m*/ public static String bytesToHexString(byte[] bytes) { StringBuilder sb = new StringBuilder(""); if (bytes == null || bytes.length <= 0) { return null; } for (int i = 0; i < bytes.length; i++) { int v = bytes[i] & 0xFF; String hv = Integer.toHexString(v); if (hv.length() < 2) { sb.append(0); } sb.append(hv); } return sb.toString(); } /** * 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; } public static String toHexString(String str) { byte[] byteArray; try { byteArray = str.getBytes("utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); byteArray = str.getBytes(); } return bytesToHexString(byteArray); } /** * Convert char to byte * * @param c * char * @return byte */ private static byte charToByte(char c) { return (byte) "0123456789ABCDEF".indexOf(c); } }