Skip to content

Instantly share code, notes, and snippets.

@Cazra
Created June 12, 2013 13:42
Show Gist options
  • Save Cazra/5765350 to your computer and use it in GitHub Desktop.
Save Cazra/5765350 to your computer and use it in GitHub Desktop.
Java String utility Converts all decimal integers in a string to hex.
/**
* Converts all decimal numbers in a string to hex.
* @param src The source string, possibly containing decimal numbers.
* @return The source string with all decimal numbers replaced by
* their equivalent hex numbers.
*/
public static String decimalInStringToHex(String src) {
String result = "";
int last = 0;
Pattern regex = Pattern.compile("(?<!\\d)((?<![a-zA-Z])\\d+(?![a-zA-Z]))+");
Matcher matcher = regex.matcher(src);
while(matcher.find()) {
long number = Long.parseLong(src.substring(matcher.start(), matcher.end()));
String hex = Long.toString(number, 16);
hex = "0x0" + hex.toUpperCase();
result += src.substring(last, matcher.start()) + hex;
last = matcher.end();
}
if(last < src.length()) {
result += src.substring(last);
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment