Java Hex Convert To fromHexStr(final String data)

Here you can find the source of fromHexStr(final String data)

Description

Convert a string with hex encoded bytes.

License

LGPL

Parameter

Parameter Description
data The data to convert

Return

The parsed byte array

Declaration

public static int[] fromHexStr(final String data) 

Method Source Code

//package com.java2s;
// Licensed under LGPLv3 - http://www.gnu.org/licenses/lgpl-3.0.txt

public class Main {
    /**//from  w  w w .j a  va  2 s .  c om
     * Parse a byte from an hex encoded string. A byte has 2 digits in the string.
     *
     * @param data The data in hex
     * @param index The index of the byte
     * @return The parsed byte as integer
     */
    public static int fromHexStr(final String data, final int index) {
        final int pos = index * 2;
        return Integer.parseInt(data.substring(pos, pos + 2), 16);
    }

    /**
     * Convert a string with hex encoded bytes. One byte is 2 characters without any spaces.
     *
     * @param data The data to convert
     * @return The parsed byte array
     */
    public static int[] fromHexStr(final String data) {
        final int length = data.length();
        if (length % 2 != 0)
            throw new IllegalArgumentException("Length of hex data must be a multiple of 2!");

        final int size = length / 2;
        final int[] result = new int[size];
        for (int i = 0; i < size; i++) {
            final int pos = i * 2;
            result[i] = Integer.parseInt(data.substring(pos, pos + 2), 16);
        }
        return result;
    }
}

Related

  1. fromHexDigit(final char c)
  2. fromHexDigit(int c)
  3. fromHexNibble(char n)
  4. fromHexNibble(final char n)
  5. fromHexShort(char a)
  6. fromHexString(byte abyte0[], int i)
  7. fromHexString(final String hexaString)
  8. fromHexString(final String hexString)
  9. fromHexString(final String s)