Java Hex Convert To fromHex(String hex)

Here you can find the source of fromHex(String hex)

Description

from Hex

License

Open Source License

Declaration

public static byte[] fromHex(String hex) 

Method Source Code

//package com.java2s;
/**/*from w w  w . ja  v  a2 s.co m*/
 * Copyright 2007-2016, Kaazing Corporation. All rights reserved.
 *
 * Licensed 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 {
    private static final byte[] FROM_HEX = new byte[] { 0x00, 0x01, 0x02,
            0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C,
            0x0D, 0x0E, 0x0F };

    public static byte[] fromHex(String hex) {

        final int len = hex.length();
        byte[] out = new byte[len >> 1];
        final char[] chars = hex.toCharArray();
        for (int i = 0; i < out.length; i++) {

            final byte i1 = hexCharToByte(chars[i << 1]);
            final byte i2 = hexCharToByte(chars[(i << 1) + 1]);
            out[i] = (byte) ((i1 << 4) + i2);

        }
        return out;
    }

    private static byte hexCharToByte(char c) {
        switch (c) {
        case '0':
            return FROM_HEX[0];
        case '1':
            return FROM_HEX[1];
        case '2':
            return FROM_HEX[2];
        case '3':
            return FROM_HEX[3];
        case '4':
            return FROM_HEX[4];
        case '5':
            return FROM_HEX[5];
        case '6':
            return FROM_HEX[6];
        case '7':
            return FROM_HEX[7];
        case '8':
            return FROM_HEX[8];
        case '9':
            return FROM_HEX[9];
        case 'A':
            return FROM_HEX[10];
        case 'B':
            return FROM_HEX[11];
        case 'C':
            return FROM_HEX[12];
        case 'D':
            return FROM_HEX[13];
        case 'E':
            return FROM_HEX[14];
        case 'F':
            return FROM_HEX[15];
        }
        return 0x00;
    }
}

Related

  1. fromHex(String hex)
  2. fromHex(String hex)
  3. fromHex(String hex)
  4. fromHex(String hex)
  5. fromHex(String hex)
  6. fromHex(String hex)
  7. fromHex(String hex)
  8. fromHex(String hex)
  9. fromHex(String hexBytes)