Here you can find the source of toBytes(String hex)
Parameter | Description |
---|---|
hex | a parameter |
public static byte[] toBytes(String hex)
//package com.java2s; //License from project: Apache License public class Main { /**//from w w w. j a va 2 s .com * Convert Hex string to byte array hex string format is: 2 char represent * one byte,can use space as separator for example, "12 1e 3d ee FF 09" * * @param hex * @return */ public static byte[] toBytes(String hex) { byte[] buff = new byte[hex.length() / 2]; int s1, s2, count = 0; for (int i = 0; i < hex.length(); i++) { if (hex.charAt(i) >= '0' && hex.charAt(i) <= '9') s1 = hex.charAt(i) - 48; else if (hex.charAt(i) >= 'A' && hex.charAt(i) <= 'F') s1 = hex.charAt(i) - 55; else if (hex.charAt(i) >= 'a' && hex.charAt(i) <= 'f') s1 = hex.charAt(i) - 87; else continue; i++; if (hex.charAt(i) >= '0' && hex.charAt(i) <= '9') s2 = hex.charAt(i) - 48; else if (hex.charAt(i) >= 'A' && hex.charAt(i) <= 'F') s2 = hex.charAt(i) - 55; else if (hex.charAt(i) >= 'a' && hex.charAt(i) <= 'f') s2 = hex.charAt(i) - 87; else continue; buff[count] = ((byte) (s1 * 16 + s2)); count++; } byte[] result = new byte[count]; System.arraycopy(buff, 0, result, 0, result.length); return result; } }