Java String to Byte Array convertStringToBytes(String string)

Here you can find the source of convertStringToBytes(String string)

Description

convert String To Bytes

License

Open Source License

Declaration

public static byte[] convertStringToBytes(String string) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    public static byte[] convertStringToBytes(String string) {
        if (string.length() % 2 != 0) {
            throw new IllegalArgumentException("Illegal HEX string '" + string
                    + "' provided! The number of character needs to be dividable by 2.");
        }/*from   www.  j  ava2s.co  m*/
        byte[] result = new byte[string.length() / 2];
        char[] chars = new char[string.length()];
        string.getChars(0, string.length(), chars, 0);
        for (int i = 0; i < string.length() / 2; i++) {
            char c = chars[2 * i];
            char c2 = chars[2 * i + 1];
            byte highHalfByte = convertHexCharacterToHalfByte(c);
            byte lowHalfByte = convertHexCharacterToHalfByte(c2);
            byte b = (byte) (highHalfByte * 16 + lowHalfByte);
            result[i] = b;
        }
        return result;
    }

    static byte convertHexCharacterToHalfByte(char character) {
        if ((character >= '0') && (character <= '9')) {
            return (byte) (character - '0');
        } else if ((character >= 'a') && (character <= 'f')) {
            return (byte) (character - 'a' + 10);
        } else if ((character >= 'A') && (character <= 'F')) {
            return (byte) (character - 'A' + 10);
        } else {
            throw new IllegalArgumentException("'" + character + "' is an illegal character in HEX code!");
        }
    }
}

Related

  1. asBytes(String hexStr)
  2. convertStringToByte(String input)
  3. convertStringToByte(String strValue)
  4. convertStringToByteArray(String input)
  5. convertStringToByteArray(String string)
  6. getBytes(String k)
  7. getBytes(String k)
  8. getBytes(String outputFile, Map queries)
  9. getBytes(String s)