CyberArmy University | Open Source Institute | CyberArmy Intelligence & Security | CyberArmy Services & Projects

Modified (Exceptions Included)


[Replies] [Reply] [View by Thread] [Help]
[Back To SNEAK Development Forum]

Posted by Cpt SAJChurchey On 2005-02-27 20:11:58
In Reply to RE: Java - Bin2Text - Second Draft Posted by Tr flamebalrog On 2005-02-26 02:06:30

Cpt
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:


Guest:
Subject:
Message:
Signature:
Optional Image Link:
http://

CyberArmy::Forum v0.6
Generated In 0.09950 seconds


About Us | Privacy Policy | Mission Statement | Help