Java Convert via ByteBuffer hexStringToBytes(String hexString)

Here you can find the source of hexStringToBytes(String hexString)

Description

hex String To Bytes

License

Apache License

Declaration

public static ByteBuffer hexStringToBytes(String hexString) 

Method Source Code

//package com.java2s;
/**/*from  w w w. j  a  v  a  2  s  .  com*/
 *  Copyright 2011 LiveRamp
 *
 *  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.
 */

import java.nio.ByteBuffer;

public class Main {
    public static ByteBuffer hexStringToBytes(String hexString) {
        hexString = hexString.replaceAll("\\W+", "");
        if (hexString.length() % 2 != 0) {
            throw new RuntimeException("Input string's size must be even.");
        }
        byte[] result = new byte[hexString.length() / 2];
        for (int i = 0; i < hexString.length(); i += 2) {
            result[i / 2] = (byte) Integer.valueOf(hexString.substring(i, i + 2), 16).intValue();
        }
        return ByteBuffer.wrap(result);
    }
}

Related

  1. hexDump(byte... b)
  2. hexDump(byte[] buffer)
  3. hexStrToStr(String hexStr)
  4. hexToAscii(byte[] src)
  5. hexToBytes(String hexStr)
  6. hexToBytes(String hexString)