Skip to content

Instantly share code, notes, and snippets.

@spangenberg
Created December 8, 2010 15:39
Show Gist options
  • Save spangenberg/733430 to your computer and use it in GitHub Desktop.
Save spangenberg/733430 to your computer and use it in GitHub Desktop.
Hexadecimal to dual
String hexString = "12345";
StringBuffer binaryString = new StringBuffer();
Integer n = 0,
dualInt = 0,
currentNumber = 0;
// hex2dual
for ( int i = hexString.length() - 1; i >= 0; i-- ) {
int a,
b = (new Double(Math.pow(16, n))).intValue();
char character = hexString.charAt(i);
if (character == 'A') {
a = 10;
} else if (character == 'B') {
a = 11;
} else if (character == 'C') {
a = 12;
} else if (character == 'D') {
a = 13;
} else if (character == 'E') {
a = 14;
} else if (character == 'F') {
a = 15;
} else {
a = Integer.parseInt((new Character(character)).toString());
}
int value = a * b;
dualInt = dualInt + value;
n++;
// System.out.println(a + " * " + b + " = " + value);
}
// dual2binary
currentNumber = dualInt;
while (currentNumber > 0) {
Integer remain = currentNumber / 2;
Integer modulo = currentNumber % 2;
binaryString.insert(0, modulo.toString());
// System.out.println(currentNumber + " : 2 = " + remain + " Rest: " + modulo);
currentNumber = remain;
}
System.out.println(binaryString.toString());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment