Java - Hex2Bin - First Draft |
||
![]() Cpt SAJChurchey When looking at this problem, you have to consider that we're not limited by a character set here. The user can type in an infinitely large expression to be converted, and as such this function needs to handle it. I thought of two different ways to accomplish this: 1. Use the BigInteger class and do the conversion mathematically (hex -> decimal -> binary). 2. Do a direct substitution, each hex digit has a unique nibble that can be directly substituted in. Considering that to do mathematical work w/ BigInteger you are working with a lot of BigInteger objects, and I figured the mathematical operations would slow the function down (Please correct me if I'm wrong). public static String hex2Bin(String str){
if(str == null || str.trim().length() == 0)
return "";
str = str.trim().toLowerCase();
if(str.matches("[^0-9a-f\\s]"))
//InvalidInputException
return "";
String[] nibbles = {
"0000",
"0001",
"0010",
"0011",
"0100",
"0101",
"0110",
"0111",
"1000",
"1001",
"1010", //a
"1011", //b
"1100", //c
"1101", //d
"1110", //e
"1111", //f
};
int strLen = str.length();
StringBuffer text = new StringBuffer(strLen * 4);
for(int i = 0;i < strLen;++i){
int digit = str.charAt(i);
if(digit >= '0' && digit <= '9')
text.append(nibbles[digit - '0']);
else if(digit >= 'a' && digit <= 'f')
text.append(nibbles[digit - 'a' + 10]);
else
text.append((char) digit);
}//end for
return text.toString();
}
Cpt SAJChurchey
C/O of Editorial OSI Staff edit0r OSI Feedback Representative Replies:
|
||
| CyberArmy::Forum v0.6 Generated In 0.06085 seconds |