Here you can find the source of convertHexStringToByteArray(String str, int numBytes, int numCharsPerByte)
Parameter | Description |
---|---|
str | a parameter |
numBytes | a parameter |
numCharsPerByte | - number of characters per byte of data |
Parameter | Description |
---|---|
NumberFormatException | an exception |
public static byte[] convertHexStringToByteArray(String str, int numBytes, int numCharsPerByte) throws NumberFormatException
//package com.java2s; /******************************************************************************* * Copyright (c) 2004, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors:/*from www . j a va2 s. c o m*/ * IBM Corporation - initial API and implementation *******************************************************************************/ public class Main { /** * Convert raw memory data to byte array * @param str * @param numBytes * @param numCharsPerByte - number of characters per byte of data * @return an array of byte, converted from a hex string * @throws NumberFormatException */ public static byte[] convertHexStringToByteArray(String str, int numBytes, int numCharsPerByte) throws NumberFormatException { if (str.length() == 0) return null; StringBuffer buf = new StringBuffer(str); // pad string with zeros int requiredPadding = numBytes * numCharsPerByte - str.length(); while (requiredPadding > 0) { buf.insert(0, "0"); //$NON-NLS-1$ requiredPadding--; } byte[] bytes = new byte[numBytes]; str = buf.toString(); // set data in memory for (int i = 0; i < bytes.length; i++) { // convert string to byte String oneByte = str.substring(i * 2, i * 2 + 2); Integer number = Integer.valueOf(oneByte, 16); if (number.compareTo(Integer.valueOf(Byte.toString(Byte.MAX_VALUE))) > 0) { int temp = number.intValue(); temp = temp - 256; String tempStr = Integer.toString(temp); Byte myByte = Byte.valueOf(tempStr); bytes[i] = myByte.byteValue(); } else { Byte myByte = Byte.valueOf(oneByte, 16); bytes[i] = myByte.byteValue(); } } return bytes; } }