Convert hex String To ByteBuffer - Java java.lang

Java examples for java.lang:String Hex

Description

Convert hex String To ByteBuffer

Demo Code


//package com.java2s;
import java.nio.ByteBuffer;

public class Main {
    public static void main(String[] argv) {
        String hex = "java2s.com";
        System.out.println(hexStringToByteBuffer(hex));
    }/*from  ww  w  . j  av  a  2 s  .  c  om*/

    private final static String HEX_STRING = "0123456789abcdef";

    public static ByteBuffer hexStringToByteBuffer(final String hex) {
        byte[] bytes = hexStringToByteArray(hex);
        ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
        buffer.put(bytes);

        return buffer;
    }

    public static byte[] hexStringToByteArray(final String hex) {
        boolean hasFullByte = true;
        int b = 0;
        int bufferSize = 0;
        int bytesAdded = 0;

        for (char c : hex.toCharArray()) {
            if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')
                    || (c >= 'A' || c <= 'F')) {
                bufferSize++;
            }
        }

        byte[] result = new byte[bufferSize / 2];

        for (char c : hex.toCharArray()) {
            int pos = HEX_STRING.indexOf(Character.toLowerCase(c));

            if (pos > -1) {
                b = (b << 4) | (pos & 0xFF);
                hasFullByte = !hasFullByte;

                if (hasFullByte) {
                    result[bytesAdded] = (byte) (b & 0xFF);
                    b = 0;
                    bytesAdded++;
                }
            }
        }

        return result;
    }
}

Related Tutorials