Here you can find the source of fromHex(final String hex)
Parameter | Description |
---|---|
hex | The hex string. |
public static final byte[] fromHex(final String hex)
//package com.java2s; /*//from ww w . j ava2 s.c o m * Copyright 2010,2014 Attribyte, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations under the License. * */ public class Main { /** * Indicates characters outside the hex alphabet. * Accepts both upper and lower-case. */ private static final int INVALID_HEX_DIGIT = -1; private static final int[] hexVals = new int[256]; /** * Convert a string of hex to bytes. * @param hex The hex string. * @return The bytes. */ public static final byte[] fromHex(final String hex) { char[] ch = hex.toCharArray(); if (ch.length % 2 != 0) { throw new UnsupportedOperationException("The hex string must contain an even number of digits"); } byte[] b = new byte[ch.length / 2]; char ch0, ch1; try { for (int i = 0; i < ch.length; i += 2) { ch0 = ch[i]; ch1 = ch[i + 1]; int v1 = hexVals[ch0]; if (v1 == INVALID_HEX_DIGIT) { throw new UnsupportedOperationException("The character, '" + ch0 + "' is not a hex digit"); } int v2 = hexVals[ch1]; if (v2 == INVALID_HEX_DIGIT) { throw new UnsupportedOperationException("The character, '" + ch1 + "' is not a hex digit"); } b[i / 2] = (byte) ((v1 << 4) | v2); } return b; } catch (IndexOutOfBoundsException e) { throw new UnsupportedOperationException("The hex string contains an invalid hex digit"); } } }