Modified (Exceptions Included) |
||
![]() Cpt SAJChurchey Alright, I hope this looks better, it incorporates flamebalrog's bit shifts as opposed to using Math.pow() in the binary to integer conversion. I've also included the exceptions to be thrown if input is invalid. Not sure exactly what the message should be that is sent to the user though: public static String Bin2Text(String str){
if(str == null || str.matches("[^01\\s]"))
throw new IllegalArgumentException("Please insert binary digits separated by spaces");
str = str.trim();
if(str.length() == 0)
throw new IllegalArgumentException("Please insert binary digits separated by whitespace");
StringTokenizer tokenizedStr = new StringTokenizer(str);
StringBuffer text = new StringBuffer();
while(tokenizedStr.hasMoreTokens()){
String binaryString = tokenizedStr.nextToken();
int bytelen = binaryString.length();
if(bytelen > 16)
throw new IllegalArgumentException("Binary value outside of UTF-16 range");
int intValue = bin2int(binaryString);
char textEquivalent = (char) intValue;
text.append(textEquivalent);
}
return text.toString();
}
public static int bin2int(String binary){
int result = 0;
int numberBits = binary.length();
for(int i = 0;i < numberBits;++i){
int bitValue = binary.charAt(i) - '0';
result = (result<<1)|bitValue;
}//end for
return result;
}
Cpt SAJChurchey
C/O of Editorial OSI Staff edit0r OSI Feedback Representative Replies:
|
||
| CyberArmy::Forum v0.6 Generated In 0.09950 seconds |