Here you can find the source of fromHex(CharSequence cs)
Parameter | Description |
---|---|
cs | the char sequence, the length must be even |
public static byte[] fromHex(CharSequence cs)
//package com.java2s; /*// ww w . j av a 2 s . c om * Copyright 2012-2014 David Karnok * * 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 { /** * Converts a character sequence of hexadecimal characters * to byte array. * @param cs the char sequence, the length must be even * @return the byte array output */ public static byte[] fromHex(CharSequence cs) { if (cs.length() % 2 != 0) { throw new IllegalArgumentException("Odd length: " + cs.length()); } byte[] r = new byte[cs.length() / 2]; for (int i = 0; i < r.length; i++) { r[i] = (byte) ((fromHex(cs.charAt(i * 2)) << 4) | fromHex(cs.charAt(i * 2 + 1))); } return r; } /** * Convert a hexadecimal character into a number. * @param c the character, 0-9a-fA-F * @return the decimal value */ private static int fromHex(char c) { if (c >= '0' && c <= '9') { return c - '0'; } if (c >= 'a' && c <= 'f') { return c - 'a' + 10; } if (c >= 'A' && c <= 'F') { return c - 'A' + 10; } throw new IllegalArgumentException("Not a hex char: " + c); } }