Here you can find the source of fromHexString(String s)
Parameter | Description |
---|---|
s | a hex string |
public static byte[] fromHexString(String s)
//package com.java2s; public class Main { /**/*from w w w . j av a 2 s . co m*/ * Convert a string containing hexadecimal characters to a byte-array. * * @param s a hex string * @return a byte array with the corresponding value */ public static byte[] fromHexString(String s) { char[] rawChars = s.toUpperCase().toCharArray(); int hexChars = 0; for (int i = 0; i < rawChars.length; i++) { if ((rawChars[i] >= '0' && rawChars[i] <= '9') || (rawChars[i] >= 'A' && rawChars[i] <= 'F')) { hexChars++; } } byte[] byteString = new byte[(hexChars + 1) >> 1]; int pos = hexChars & 1; for (int i = 0; i < rawChars.length; i++) { if (rawChars[i] >= '0' && rawChars[i] <= '9') { byteString[pos >> 1] <<= 4; byteString[pos >> 1] |= rawChars[i] - '0'; } else if (rawChars[i] >= 'A' && rawChars[i] <= 'F') { byteString[pos >> 1] <<= 4; byteString[pos >> 1] |= rawChars[i] - 'A' + 10; } else { continue; } pos++; } return byteString; } /** * Rewrite a byte array as a char array * * @param input - * the byte array * @return char array */ public static char[] toCharArray(byte[] input) { char[] result = new char[input.length]; for (int i = 0; i < input.length; i++) { result[i] = (char) input[i]; } return result; } }