Java Convert via ByteBuffer toBuffer(String spacedHex)

Here you can find the source of toBuffer(String spacedHex)

Description

Convert the spaced hex form of a String into a ByteBuffer.

License

CDDL license

Parameter

Parameter Description
spacedHex a parameter

Declaration

public static ByteBuffer toBuffer(String spacedHex) 

Method Source Code


//package com.java2s;
/*//from   ww  w. ja va 2  s.  co  m
 * The contents of this file are subject to the terms of the Common Development and
 * Distribution License (the License). You may not use this file except in compliance with the
 * License.
 *
 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
 * specific language governing permission and limitations under the License.
 *
 * When distributing Covered Software, include this CDDL Header Notice in each file and include
 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
 * Header, with the fields enclosed by brackets [] replaced by your own identifying
 * information: "Portions copyright [year] [name of copyright owner]".
 *
 * Copyright 2015 LDS
 */

import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;

public class Main {
    /**
     * Convert the spaced hex form of a String into a ByteBuffer.
     *
     * @param spacedHex
     * @return
     */
    public static ByteBuffer toBuffer(String spacedHex) {
        return ByteBuffer.wrap(toByteArray(spacedHex));
    }

    /**
     * Convert the spaced hex form of a String into a byte array.
     *
     * @param spacedHex
     * @return
     */
    public static byte[] toByteArray(String spacedHex) {
        int idx = 0;
        int len = spacedHex.length();
        StringBuilder sb = new StringBuilder();
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();

        while (idx < len) {
            char chr = spacedHex.charAt(idx++);

            if (chr != ' ') {
                sb.setLength(0);
                sb.append(chr);
                sb.append(spacedHex.charAt(idx++));
                int i = Integer.parseInt(sb.toString(), 16);
                byte b = ((byte) i);
                bytes.write(b);
            }
        }

        return bytes.toByteArray();
    }
}

Related

  1. toBuffer(boolean[] src, int offset)
  2. toBuffer(byte[] arr)
  3. toBuffer(byte[] arr)
  4. toBuffer(int[] array)
  5. toBuffer(Serializable obj)
  6. toByte(char data)
  7. toByte(final char[] charArray)
  8. toByte(int input, int count)
  9. toByteArray(BitSet bits)