Last active
August 29, 2015 14:14
-
-
Save klmr/2722423aa651a44cf0d2 to your computer and use it in GitHub Desktop.
Parsing and writing numbers in different bases
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
package demo; | |
public class Numbers { | |
static final String hexDigits = "0123456789ABCDEF"; | |
static final String decDigits = "0123456789"; | |
static int fromBaseRepresentation(final String value, final String digits) { | |
final int base = digits.length(); | |
int result = 0; | |
for (final char c : value.toCharArray()) { | |
result *= base; | |
result += digits.indexOf(c); | |
} | |
return result; | |
} | |
static String toBaseRepresentation(int value, final String digits) { | |
final int base = digits.length(); | |
final StringBuilder sb = new StringBuilder(); | |
while (value > 0) { | |
final int digit = value % base; | |
value /= base; | |
sb.append(digits.charAt(digit)); | |
} | |
return sb.reverse().toString(); | |
} | |
static int fromHex(final String value) { | |
return fromBaseRepresentation(value, hexDigits); | |
} | |
static int fromDec(final String value) { | |
return fromBaseRepresentation(value, decDigits); | |
} | |
static String toHex(final int value) { | |
return toBaseRepresentation(value, hexDigits); | |
} | |
static String toDec(final int value) { | |
return toBaseRepresentation(value, decDigits); | |
} | |
public static void main(final String[] args) { | |
final String hex = args[0]; | |
final int value = fromHex(hex); | |
final String dec = toDec(value); | |
System.out.printf("Hex input: %s, decimal output: %s\n", hex, dec); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment