diff options
Diffstat (limited to 'src/com')
-rw-r--r-- | src/com/isode/stroke/stringcodecs/Hexify.java | 24 |
1 files changed, 22 insertions, 2 deletions
diff --git a/src/com/isode/stroke/stringcodecs/Hexify.java b/src/com/isode/stroke/stringcodecs/Hexify.java index 8dda1c2..52facb4 100644 --- a/src/com/isode/stroke/stringcodecs/Hexify.java +++ b/src/com/isode/stroke/stringcodecs/Hexify.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011 Isode Limited, London, England. + * Copyright (c) 2011-2012 Isode Limited, London, England. * All rights reserved. */ /* @@ -13,7 +13,7 @@ import com.isode.stroke.base.ByteArray; public class Hexify { public static String hexify(byte datum) { - return String.format("%x", new Byte(datum)); + return String.format("%02x", new Byte(datum)); } public static String hexify(ByteArray data) { @@ -23,4 +23,24 @@ public class Hexify { } return result.toString(); } + + + + public static ByteArray unhexify(String hexstring) { + if (hexstring.length() % 2 != 0) { + return new ByteArray(); + } + byte[] result = new byte[hexstring.length() / 2]; + for (int pos = 0; pos < hexstring.length() - 1; pos += 2) { + char c; + c = hexstring.charAt(pos); + int a = (c>='0'&&c<='9') ? c-'0' : (c>='A'&&c<='Z') ? c-'A' + 10 : (c>='a'&&c<='z') ? c-'a' + 10 : -1; + c = hexstring.charAt(pos+1); + int b = (c>='0'&&c<='9') ? c-'0' : (c>='A'&&c<='Z') ? c-'A' + 10 : (c>='a'&&c<='z') ? c-'a' + 10 : -1; + if (a == -1 || b == -1) return new ByteArray(); // fail + result[pos/2] = (byte) ((a << 4) | b); + + } + return new ByteArray(result); + } } |