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;
//License from project: Open Source License 

public class Main {
    public static byte[] fromHex(String hex) {
        char[] hexChars = hex.toCharArray();
        int n = hexChars.length;
        byte[] bytes = new byte[(int) Math.ceil(n / 2.0)];

        for (int c = 0; c < n; c += 2) {
            byte i = (byte) (charToNum(hexChars[c]) << 4);
            byte j = (c + 1 < n) ? charToNum(hexChars[c + 1]) : 0;

            bytes[c / 2] = (byte) (i + j);
        }/*from  w ww. jav  a 2  s  .co m*/

        return bytes;
    }

    private static byte charToNum(char c) {
        switch (c) {
        case '0':
            return 0x0;
        case '1':
            return 0x1;
        case '2':
            return 0x2;
        case '3':
            return 0x3;
        case '4':
            return 0x4;
        case '5':
            return 0x5;
        case '6':
            return 0x6;
        case '7':
            return 0x7;
        case '8':
            return 0x8;
        case '9':
            return 0x9;
        case 'a':
        case 'A':
            return 0xA;
        case 'b':
        case 'B':
            return 0xB;
        case 'c':
        case 'C':
            return 0xC;
        case 'd':
        case 'D':
            return 0xD;
        case 'e':
        case 'E':
            return 0xE;
        case 'f':
        case 'F':
            return 0xF;
        default:
            throw new NumberFormatException(String.format("%c is not a valid hex digit", c));
        }
    }
}

Related

  1. fromHex(String encoded)
  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 hex)