Last active
August 29, 2015 14:19
-
-
Save wjx/5b99ea7ed1f03f344f20 to your computer and use it in GitHub Desktop.
hexStringToBytes/bytesToHexString
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
android/frameworks/opt/telephony/src/java/com/android/internal/telephony/uicc/IccUtils.java | |
static int | |
hexCharToInt(char c) { | |
if (c >= '0' && c <= '9') return (c - '0'); | |
if (c >= 'A' && c <= 'F') return (c - 'A' + 10); | |
if (c >= 'a' && c <= 'f') return (c - 'a' + 10); | |
throw new RuntimeException ("invalid hex char '" + c + "'"); | |
} | |
/** | |
* Converts a hex String to a byte array. | |
* | |
* @param s A string of hexadecimal characters, must be an even number of | |
* chars long | |
* | |
* @return byte array representation | |
* | |
* @throws RuntimeException on invalid format | |
*/ | |
public static byte[] | |
hexStringToBytes(String s) { | |
byte[] ret; | |
if (s == null) return null; | |
int sz = s.length(); | |
ret = new byte[sz/2]; | |
for (int i=0 ; i <sz ; i+=2) { | |
ret[i/2] = (byte) ((hexCharToInt(s.charAt(i)) << 4) | |
| hexCharToInt(s.charAt(i+1))); | |
} | |
return ret; | |
} | |
/** | |
* Converts a byte array into a String of hexadecimal characters. | |
* | |
* @param bytes an array of bytes | |
* | |
* @return hex string representation of bytes array | |
*/ | |
public static String | |
bytesToHexString(byte[] bytes) { | |
if (bytes == null) return null; | |
StringBuilder ret = new StringBuilder(2*bytes.length); | |
for (int i = 0 ; i < bytes.length ; i++) { | |
int b; | |
b = 0x0f & (bytes[i] >> 4); | |
ret.append("0123456789abcdef".charAt(b)); | |
b = 0x0f & bytes[i]; | |
ret.append("0123456789abcdef".charAt(b)); | |
} | |
return ret.toString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment