Android String to Byte Array Convert fromString(String str)

Here you can find the source of fromString(String str)

Description

Convert a hex-encoded String to binary data

Parameter

Parameter Description
str A String containing the encoded data

Return

An array containing the binary data, or null if the string is invalid

Declaration

public static byte[] fromString(String str) 

Method Source Code

//package com.java2s;
import java.io.*;

public class Main {
    private static final String Base16 = "0123456789ABCDEF";

    /**/* w ww .java2s.c  o  m*/
     * Convert a hex-encoded String to binary data
     * @param str A String containing the encoded data
     * @return An array containing the binary data, or null if the string is invalid
     */
    public static byte[] fromString(String str) {
        ByteArrayOutputStream bs = new ByteArrayOutputStream();
        byte[] raw = str.getBytes();
        for (int i = 0; i < raw.length; i++) {
            if (!Character.isWhitespace((char) raw[i]))
                bs.write(raw[i]);
        }
        byte[] in = bs.toByteArray();
        if (in.length % 2 != 0) {
            return null;
        }

        bs.reset();
        DataOutputStream ds = new DataOutputStream(bs);

        for (int i = 0; i < in.length; i += 2) {
            byte high = (byte) Base16.indexOf(Character
                    .toUpperCase((char) in[i]));
            byte low = (byte) Base16.indexOf(Character
                    .toUpperCase((char) in[i + 1]));
            try {
                ds.writeByte((high << 4) + low);
            } catch (IOException e) {
            }
        }
        return bs.toByteArray();
    }
}

Related

  1. fromString(String binary)
  2. hexStringToByteArray(String hexa)
  3. toByte(String hexString)
  4. toByte(String hexString)
  5. toBytes(final String str)