Java Byte Array Create toByteArrayFromString(String value, int radix)

Here you can find the source of toByteArrayFromString(String value, int radix)

Description

Converts a string into a byte array.

License

Apache License

Declaration

public static byte[] toByteArrayFromString(String value, int radix) 

Method Source Code

//package com.java2s;
/*/*from w  w w . j ava2s .co m*/
 // Licensed to DynamoBI Corporation (DynamoBI) under one
 // or more contributor license agreements.  See the NOTICE file
 // distributed with this work for additional information
 // regarding copyright ownership.  DynamoBI licenses this file
 // to you 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.
 */

public class Main {
    /**
     * Converts a string into a byte array. The inverse of {@link
     * #toStringFromByteArray(byte[], int)}.
     */
    public static byte[] toByteArrayFromString(String value, int radix) {
        assert 16 == radix : "Specified string to byte array conversion not supported yet";
        assert (value.length() % 2) == 0 : "Hex binary string must contain even number of characters";

        byte[] ret = new byte[value.length() / 2];
        for (int i = 0; i < ret.length; i++) {
            int digit1 = Character.digit(value.charAt(i * 2), radix);
            int digit2 = Character.digit(value.charAt((i * 2) + 1), radix);
            assert (digit1 != -1) && (digit2 != -1) : "String could not be converted to byte array";
            ret[i] = (byte) ((digit1 * radix) + digit2);
        }
        return ret;
    }
}

Related

  1. toByteArray(String[] anArray)
  2. toByteArray1D(int[][] d)
  3. toByteArrayBE(byte b)
  4. toByteArrayForPBE(char[] chars)
  5. toByteArrayFromPositiveInts(int[] inInts)
  6. toByteArrayLE(int value)
  7. toByteArrayMM(int value)
  8. toByteArrayNoConversion(String textz)
  9. toByteArrays(String s)