Java Byte Array Create toBytes(final String hexaString)

Here you can find the source of toBytes(final String hexaString)

Description

Convert a base 16 string into bytes.

License

Open Source License

Parameter

Parameter Description
hexaString a parameter

Declaration

public static byte[] toBytes(final String hexaString) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2007, 2013 compeople AG 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  ww  w  .ja v a 2  s.  c  o  m
 *    compeople AG - initial API and implementation
 *******************************************************************************/

public class Main {
    /**
     * Convert a base 16 string into bytes.
     * 
     * @param hexaString
     * @return
     */
    public static byte[] toBytes(final String hexaString) {
        if (hexaString.length() % 2 == 1) {
            throw new IllegalArgumentException("String length must be even."); //$NON-NLS-1$
        }
        final byte[] bytes = new byte[hexaString.length() / 2];
        for (int bi = 0, i = 0; bi < bytes.length; bi++) {
            int b = Character.digit(hexaString.charAt(i++), 16) << 4;
            b |= Character.digit(hexaString.charAt(i++), 16);
            bytes[bi] = (byte) b;
        }
        return bytes;
    }
}

Related

  1. toBytes(char[] cbuf, byte[] bs)
  2. toBytes(char[] chars)
  3. toBytes(final byte[] s, final int off, final int len)
  4. toBytes(final long n)
  5. toBytes(final long val)
  6. toBytes(final String str)
  7. toBytes(final String text)
  8. toBytes(int data)
  9. toBytes(int data)