Created
June 12, 2013 13:42
-
-
Save Cazra/5765350 to your computer and use it in GitHub Desktop.
Java String utility Converts all decimal integers in a string to hex.
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
/** | |
* 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