Here you can find the source of toBytesFromString(String s)
Returns a byte array from a string of hexadecimal digits.
Parameter | Description |
---|---|
s | a string of hexadecimal ASCII characters |
public static byte[] toBytesFromString(String s)
//package com.java2s; // under the terms of the GNU General Public License as published by the Free public class Main { /**/*from w w w . j a v a 2s .c om*/ * <p>Returns a byte array from a string of hexadecimal digits.</p> * * @param s a string of hexadecimal ASCII characters * @return the decoded byte array from the input hexadecimal string. */ public static byte[] toBytesFromString(String s) { int limit = s.length(); byte[] result = new byte[((limit + 1) / 2)]; int i = 0, j = 0; if ((limit % 2) == 1) { result[j++] = (byte) fromDigit(s.charAt(i++)); } while (i < limit) { result[j++] = (byte) ((fromDigit(s.charAt(i++)) << 4) | fromDigit(s.charAt(i++))); } return result; } /** * <p>Returns a number from <code>0</code> to <code>15</code> corresponding * to the designated hexadecimal digit.</p> * * @param c a hexadecimal ASCII symbol. */ public static int fromDigit(char c) { if (c >= '0' && c <= '9') { return c - '0'; } else if (c >= 'A' && c <= 'F') { return c - 'A' + 10; } else if (c >= 'a' && c <= 'f') { return c - 'a' + 10; } else throw new IllegalArgumentException("Invalid hexadecimal digit: " + c); } }