Android String to Hex Byte Array Convert fromHexString(String s)

Here you can find the source of fromHexString(String s)

Description

from Hex String

Declaration

public static byte[] fromHexString(String s) 

Method Source Code

//package com.java2s;

public class Main {
    public static byte[] fromHexString(String s) {
        char[] rawChars = s.toUpperCase().toCharArray();

        int hexChars = 0;
        for (char rawChar1 : rawChars) {
            if ((rawChar1 >= '0' && rawChar1 <= '9')
                    || (rawChar1 >= 'A' && rawChar1 <= 'F')) {
                hexChars++;//from  w ww  . jav a  2  s  .  c o  m
            }
        }

        byte[] byteString = new byte[(hexChars + 1) >> 1];

        int pos = hexChars & 1;

        for (char rawChar : rawChars) {
            if (rawChar >= '0' && rawChar <= '9') {
                byteString[pos >> 1] <<= 4;
                byteString[pos >> 1] |= rawChar - '0';
            } else if (rawChar >= 'A' && rawChar <= 'F') {
                byteString[pos >> 1] <<= 4;
                byteString[pos >> 1] |= rawChar - 'A' + 10;
            } else {
                continue;
            }
            pos++;
        }

        return byteString;
    }
}

Related

  1. hexStringToBytes(String hexString)
  2. stringToHex(String ids)
  3. hexStringToBytes(String s)
  4. hexStringToBytes(String hexString, int offset, int count)
  5. fromHex(String dataString)
  6. hexDecode(String data)