Java tutorial
//package com.java2s; /* * jPOS Project [http://jpos.org] * Copyright (C) 2000-2012 Alejandro P. Revilla * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ public class Main { /** * @param b source byte array * @param offset starting offset * @param len number of bytes in destination (processes len*2) * @return byte[len] */ public static byte[] hex2byte(byte[] b, int offset, int len) { byte[] d = new byte[len]; for (int i = 0; i < len * 2; i++) { int shift = i % 2 == 1 ? 0 : 4; d[i >> 1] |= Character.digit((char) b[offset + i], 16) << shift; } return d; } /** * @param s source string (with Hex representation) * @return byte array */ public static byte[] hex2byte(String s) { if (s.length() % 2 == 0) { return hex2byte(s.getBytes(), 0, s.length() >> 1); } else { // Padding left zero to make it even size #Bug raised by tommy return hex2byte("0" + s); } } }