Java Byte Array Create toByteArray(String string)

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

Description

to Byte Array

License

Open Source License

Declaration

private static byte[] toByteArray(String string) 

Method Source Code

//package com.java2s;
/*//from  w  w w  . j a v a2s.c  om
 * Copyright (c) 2015 Nikolay Zapolnov (zapolnov@gmail.com).
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

public class Main {
    private static byte[] toByteArray(String string) {
        int count = string.length() / 2;
        byte[] result = new byte[count];
        for (int i = 0; i < count; i++) {
            char c1 = string.charAt(i * 2);
            char c2 = string.charAt(i * 2 + 1);
            result[i] = (byte) ((unhex(c1) << 4) | unhex(c2));
        }
        return result;
    }

    private static int unhex(char c) {
        if (c >= '0' && c <= '9')
            return c - '0';
        if (c >= 'a' && c <= 'f')
            return c - 'a' + 10;
        if (c >= 'A' && c <= 'F')
            return c - 'A' + 10;
        throw new RuntimeException(String.format("Invalid hexadecimal digit '%c'.", c));
    }
}

Related

  1. toByteArray(String source)
  2. toByteArray(String str)
  3. toByteArray(String str)
  4. toByteArray(String str)
  5. toByteArray(String str, String separator)
  6. toByteArray(String string)
  7. toByteArray(String strTransInfo)
  8. toByteArray(String uid)
  9. toByteArray(String value)