Skip to content

Instantly share code, notes, and snippets.

@firatkucuk
Created June 12, 2017 18:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save firatkucuk/b629196dfe873bbd14383fdc198fb20b to your computer and use it in GitHub Desktop.
Save firatkucuk/b629196dfe873bbd14383fdc198fb20b to your computer and use it in GitHub Desktop.
Try to convert arbitrary length string decimal to string hexadecimal
public class Decimal2Hex {
private static String[] HEX = new String[]{
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"
};
public static String convert(final String numberText) {
final Object[] result = divideTo16(numberText);
final String quotient = (String) result[0];
final String hexValue = HEX[(int) result[1]];
if (quotient.length() < 3) { // It's not rational to parse every quotient
final int intQuotient = Integer.parseInt(quotient);
if (intQuotient < 16) {
return HEX[intQuotient] + hexValue;
}
}
return convert(quotient) + hexValue;
}
private static Object[] divideTo16(final String numberText) {
final Object[] result = divideFragmentTo16(
numberText, 0, numberText.length() > 1 ? 2 : 1, "", 0
);
// Simply removing unnecessary 0 prefix
String quotient = (String) result[0];
if (quotient.length() > 1 && quotient.startsWith("0")) {
quotient = quotient.substring(1);
}
return new Object[]{quotient, result[1]};
}
private static Object[] divideFragmentTo16(
final String numberText,
final int start,
int stop,
final String totalQuotient,
final int reminder
) {
final int number = Integer.parseInt(reminder + numberText.substring(start, stop));
final int newReminder = number % 16;
final String quotient = totalQuotient + number / 16;
if (stop + 1 > numberText.length()) {
return new Object[]{
quotient,
newReminder
};
}
return divideFragmentTo16(
numberText, stop, stop + 1, quotient, newReminder
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment