+ public static byte[] fromHex(String s) {
+ if(!s.startsWith("0x")) {
+ return fromHexNo0x(s);
+ }
+ byte b;
+ int c;
+ byte[] ba;
+ int extra = s.length()%2; // odd requires extra
+ ba = new byte[(s.length()-2)/2 + extra];
+ boolean high = extra==0;
+
+ int idx;
+ for (int i=2;i<s.length();++i) {
+ c = s.charAt(i);
+ if (c>=0x30 && c<=0x39) {
+ b=(byte)(c-0x30);
+ } else if (c>=0x61 && c<=0x66) {
+ b=(byte)(c-0x57); // account for "A"
+ } else if (c>=0x41 && c<=0x46) {
+ b=(byte)(c-0x37);
+ } else {
+ return null;
+ }
+ idx = (i-2+extra)/2;
+ if (high) {
+ ba[idx]=(byte)(b<<4);
+ high = false;
+ } else {
+ ba[idx]|=b;
+ high = true;
+ }
+ }
+ return ba;
+ }
+
+ /**
+ * Does not expect to start with "0x"
+ * if Any Character doesn't match, it returns null;
+ *
+ * @param s
+ * @return
+ */
+ public static byte[] fromHexNo0x(String s) {
+ byte b;
+ int c;
+ byte[] ba;
+ int extra = s.length()%2; // odd requires extra byte to store
+ ba = new byte[(s.length())/2 + extra];
+ boolean high = extra==0;
+
+ int idx;
+ for (int i=0;i<s.length();++i) {
+ c = s.charAt(i);
+ if (c>=0x30 && c<=0x39) {
+ b=(byte)(c-0x30);
+ } else if (c>=0x61 && c<=0x66) {
+ b=(byte)(c-0x57); // account for "A"
+ } else if (c>=0x41 && c<=0x46) {
+ b=(byte)(c-0x37);
+ } else {
+ return null;
+ }
+ idx = (i+extra)/2;
+ if (high) {
+ ba[idx]=(byte)(b<<4);
+ high = false;
+ } else {
+ ba[idx]|=b;
+ high = true;
+ }
+ }
+ return ba;
+ }