14 Replies Latest reply: Feb 12, 2009 10:03 PM by 807588 RSS

    How long can a string be?

    807588
      EDIT: The diagram came out bad but basically all the numbers are lined up evenly to the right and the x designates which numbers will be added

      Basically I'm making a program that reads in two binary numbers, does binary addition, and then convert it to decimal representation. Basically I'm lining up all the powers of twos and adding them and I store the result of each column in a string and I basically keep updating that string add the next column result. Here's a representation of what I'm doing:

      binary#: 10101101 = 181 base 10
              
                    1   x  
                    2
                    4   x  
                    8
                  16   x
                  32   x
                  64
                128   x
      -------------------------
                  21   x
      -------------------------
                  8    x
      ------------------------
                1     x
      The trick to this program is it has to work for 100 bit binary numbers and mine works up until like the 35th bit so I'm guessing it has to do with String size limit if there is one? Does anyone have an idea on how else I can store the result of each column if this is the case?

      Edited by: ChrisTheSixth on Feb 12, 2009 10:05 PM
        • 1. Re: How long can a string be?
          807588
          Since a string is ostensibly backed by a char[] and the maximum length of an array is Integer.MAX_VALUE, a string - in theory - can be Integer.MAX_VALUE characters in length. Truth is, you're far more likely to run out of RAM first.
          I'm guessing it has to do with String size limit if there is one?
          Probably not. Can you post an SSCCE?

          ~
          • 2. Re: How long can a string be?
            807588
            In theory a String can be up to 2,147,483,647 characters though you'd likely run into some other problems before that.

            I don't really understand any of your explanation though so I don't know how big a String you're trying to use here. What I would say is that storing what is numeric data in a String is a mistake. You should store numbers as numbers in your program and then you can format these numbers as Strings later for display.

            I also don't know what "mine works up until like the 35th bit" means. Is the program running out of memory? Do you get an error of any kind? Or are the results wrong. Unless the program is crashing there is a logic bug in your code.
            • 3. Re: How long can a string be?
              807588
              ChrisTheSixth wrote:
              Basically I'm lining up all the powers of twos and adding them and I store the result of each column in a string and I basically keep updating that string add the next column result.
              Why? Just perform the calculation and print out the result. No need to keep a bunch of Strings with each one getting longer than the previous.
              • 4. Re: How long can a string be?
                807588
                Data file to open?(include extention) input.txt
                Opened file: input.txt
                
                Binary Addition to be performed on: 
                
                Binary #1: 0110010011
                Binary #2: 0011001011
                
                Binary Representation: 1001011110
                Hex Representation: 25E
                Decimal Representation: 606
                
                ***Which is correct***
                
                Data file to open?(include extention) input.txt
                Opened file: input.txt
                
                Binary Addition to be performed on: 
                
                Binary #1: 011001001101100100110110010011011001001101100100110110010011
                Binary #2: 001100101100110010110011001011001100101100110010110011001011
                
                Binary Representation: 100101111010010111101001011110100101111010010111101001011110
                Hex Representation: 97A5E97A5E97A5E
                Decimal Representation: 9138848462
                
                
                ***The decimal part is wrong***
                I'm using this site to check my answer: http://www.mathsisfun.com/binary-decimal-hexadecimal-converter.html
                So its either I'm right or the site is wrong
                • 5. Re: How long can a string be?
                  807588
                  So its either I'm right or the site is wrong
                  Neither. ;o)

                  You're not right and the site isn't wrong. Show your code (and Google "SSCCE").

                  ~
                  • 6. Re: How long can a string be?
                    807588
                    Whose results are these? Yours?

                    the decimal value is wrong. It should be 682962298916665950

                    By the way you can check this sort of thing using the calculator in just about any OS. Just use the scientific mode and you should find a way to change the display between hex, binary and decimal.
                    • 7. Re: How long can a string be?
                      807588
                      cotton.m wrote:
                      By the way you can check this sort of thing using the calculator in just about any OS.
                      Or in Java with:
                      System.out.println(new BigInteger("100101111010010111101001011110100101111010010111101001011110", 2));
                      ~
                      • 8. Re: How long can a string be?
                        807588
                        Sorry if this code is hard to read, if you get confuse in my code just tell me and I'll explain
                        private static String dec(String str)
                             {
                                  String decString = "";
                                  int count=0, count2=0, biggest=0, num=0, carry=0, index=0, sum=0, place=0, start=0, length=1;
                                  int[] binary,power,toBeAdded;
                                  
                                  binary= new int[str.length()];
                                  power = new int[str.length()];
                                  
                                  for(int i=0;i<str.length();i++) // puts binary number in an array
                                       binary[i] = Integer.parseInt(Character.toString(str.charAt(i)));
                                  for(int i=str.length()-1;i>=0;i--) // sets the powers of 2 array
                                  {
                                       power[i] = (int)Math.pow(2.0,index);
                                       index++;
                                  }
                                  
                                  for(int i=0;i<binary.length;i++)
                                       if(binary[i] == 1)
                                            count++;
                                  toBeAdded = new int[count];
                                  
                                  for(int i=binary.length-1;i>=0;i--) // powers of 2 where there is a 1 in binary array
                                       if(binary[i] == 1)
                                       {
                                            toBeAdded[count2] = power;
                                            count2++;
                                       }
                                  biggest = Integer.toString(toBeAdded[toBeAdded.length-1]).length(); // gets the size of the biggest power 2
                                  
                                  for(int i=biggest;i>0;i--) // number of places of biggest number
                                  {
                                       for(int j=start;j<toBeAdded.length;j++)
                                       {
                                            num = Integer.parseInt(Character.toString(Integer.toString(toBeAdded[j]).charAt(Integer.toString(toBeAdded[j]).length()-1+place))); // gets the last index of the number
                                            sum += num;
                                       }
                                       sum += carry;
                                       if(sum > 9)
                                       {
                                            carry = Integer.parseInt(Integer.toString(sum).substring(0,Integer.toString(num).length()));
                                            decString += Integer.toString(sum).charAt(Integer.toString(sum).length()-1);
                                       }
                                       else
                                       {
                                            carry = 0;
                                            decString += Integer.toString(sum).charAt(Integer.toString(sum).length()-1);
                                       }
                                       sum = 0;
                                       place--;
                                       for(int k=0; k<toBeAdded.length;k++)
                                            if(Integer.toString(toBeAdded[k]).length() > length)
                                            {
                                                 length = Integer.toString(toBeAdded[k]).length();
                                                 start = k;
                                                 break;
                                            }
                                  }
                                  return reverse(decString); // I do this because the the numbers in the string is stored backwards and reverse() returns the string reversed
                             }
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
                        • 9. Re: How long can a string be?
                          807588
                          Sorry if this code is hard to read
                          1) Didn't Google "SSCCE", did ya?

                          2) If your code is hard to read or understand, it should be Refactored.
                          if you get confuse in my code just tell me and I'll explain
                          3) GOTO 2

                          ~

                          P.S. With all due respect, you should research and study until you discover a new algorithm. The code you've posted is as bad as it gets.
                          • 10. Re: How long can a string be?
                            807588
                            sorry about that, hope this is better:
                            btw you'll need to make a .txt file with to two binary numbers, one on each line.
                            import java.io.File;
                            import java.io.IOException;
                            import java.util.Scanner;
                            import java.lang.Math;
                            
                            public class ConversionCalc 
                            {
                                 private static char carry = '0';
                                 
                                 // main method
                                 public static void main(String [] args) throws Exception
                                 {
                                      String binary1 = "";
                                      String binary2 = "";
                                      Scanner scan = openTextFile(getFileName(true,args,"Data file to open?(include extention) "));
                                      
                                      binary1 = scan.nextLine();
                                      binary2 = scan.nextLine();
                            
                                      System.out.println("Binary Addition to be performed on: \n");
                                      System.out.println("Binary #1: " + binary1 + "\n" + "Binary #2: " + binary2 + "\n");
                                      //System.out.println("Binary Representation: " + binary(binary1,binary2));
                                      //System.out.println("Hex Representation: " + hex(binary(binary1,binary2)));
                                      System.out.println("Decimal Representation: " + dec(binary(binary1,binary2)));
                                           
                                      scan.close();
                                 }
                                 
                                 // Opens the text file and allows access to the elements
                                 private static Scanner openTextFile(String fileName) throws IOException 
                                 {
                                      Scanner s = new Scanner(new File(fileName));
                                      System.out.println("Opened file: " + fileName); 
                                      System.out.println();
                                      return s;
                                 } 
                                 
                                 // Gets file name from argument from command prompt
                                 private static String getFileName(Boolean shouldPrompt, String [] strings, String prompt) 
                                 {
                                      if (shouldPrompt || strings.length == 0) 
                                      {
                                           Scanner s = new Scanner( System.in );
                                           System.out.print(prompt);
                                           return s.nextLine();
                                      }
                                      else
                                      {     
                                           return strings[0];
                                      }
                                 }
                                 
                                 private static String dec(String str)
                                 {
                                      String decString = "";
                                      int count=0, count2=0, biggest=0, num=0, carry=0, index=0, sum=0, place=0, start=0, length=1;
                                      int[] binary,power,toBeAdded;
                                      
                                      binary= new int[str.length()];
                                      power = new int[str.length()];
                                      
                                      for(int i=0;i<str.length();i++) // puts binary number in an array
                                           binary[i] = Integer.parseInt(Character.toString(str.charAt(i)));
                                      for(int i=str.length()-1;i>=0;i--) // sets the powers of 2 array
                                      {
                                           power[i] = (int)Math.pow(2.0,index);
                                           index++;
                                      }
                                      
                                      for(int i=0;i<binary.length;i++)
                                           if(binary[i] == 1)
                                                count++;
                                      toBeAdded = new int[count];
                                      
                                      for(int i=binary.length-1;i>=0;i--) // powers of 2 where there is a 1 in binary array
                                           if(binary[i] == 1)
                                           {
                                                toBeAdded[count2] = power;
                                                count2++;
                                           }
                                      biggest = Integer.toString(toBeAdded[toBeAdded.length-1]).length(); // gets the size of the biggest power 2
                                      
                                      for(int i=biggest;i>0;i--) // number of places of biggest number
                                      {
                                           for(int j=start;j<toBeAdded.length;j++)
                                           {
                                                num = Integer.parseInt(Character.toString(Integer.toString(toBeAdded[j]).charAt(Integer.toString(toBeAdded[j]).length()-1+place))); // gets the last index of the number
                                                sum += num;
                                           }
                                           sum += carry;
                                           if(sum > 9)
                                           {
                                                carry = Integer.parseInt(Integer.toString(sum).substring(0,Integer.toString(num).length()));
                                                decString += Integer.toString(sum).charAt(Integer.toString(sum).length()-1);
                                           }
                                           else
                                           {
                                                carry = 0;
                                                decString += Integer.toString(sum).charAt(Integer.toString(sum).length()-1);
                                           }
                                           sum = 0;
                                           place--;
                                           for(int k=0; k<toBeAdded.length;k++)
                                                if(Integer.toString(toBeAdded[k]).length() > length)
                                                {
                                                     length = Integer.toString(toBeAdded[k]).length();
                                                     start = k;
                                                     break;
                                                }
                                      }
                                      return reverse(decString);
                                 }
                            private static String reverse(String str)
                                 {
                                      String rev = "";
                                      
                                      for(int i=str.length()-1;i>=0;i--)
                                           rev += str.charAt(i);
                                      return rev;
                                 }
                            }
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                
                            • 11. Re: How long can a string be?
                              807588
                              sorry about that, hope this is better:
                              Won't compile. Where's your binary() method? And please, really Google "SSCCE" this time and read the whole thing. File IO has nothing to do with the problem you're having, so it shouldn't be in the code you post.

                              ~
                              • 12. Re: How long can a string be?
                                807588
                                add these
                                private static String binary(String i1, String i2)
                                     {
                                          String temp = "";
                                          String sum = "";
                                          
                                          for(int i=i1.length()-1;i>=0;i--)
                                               temp += binaryAddition(i1.charAt(i),i2.charAt(i));
                                          if(carry == '1')
                                               sum += "1";
                                          for(int i=temp.length()-1;i>=0;i--)
                                               sum += temp.charAt(i);
                                          carry = '0';
                                          return sum;
                                     }
                                     
                                     private static String binaryAddition(char input1, char input2)
                                     {
                                          if(carry == '1')
                                          {
                                               if(input1 == '1' && input2 == '1')
                                               {
                                                    return "1";
                                               }
                                               else if((input1 == '0' && input2 == '1') || (input2 == '0' && input1 == '1'))
                                               {
                                                    return "0";
                                               }
                                               else
                                               {
                                                    carry = '0';
                                                    return "1";
                                               }
                                          }
                                          else
                                          {
                                               if(input1 == '1' && input2 == '1')
                                               {
                                                    carry = '1';
                                                    return "0";
                                               }
                                               else if((input1 == '0') && (input2 == '1') || (input2 == '0' && input1 == '1'))
                                               {
                                                    return "1";
                                               }
                                               else
                                               {
                                                    return "0";
                                               }
                                          }          
                                     }
                                • 13. Re: How long can a string be?
                                  807588
                                  ChrisTheSixth wrote:
                                  add these
                                  No. That's too much trouble. Here is an example of an SSCCE that shows at least part of the problem you're having:
                                  import java.math.BigInteger;
                                  
                                  public class ConversionCalc {
                                  
                                       public static void main(String[] args) throws Exception {
                                            String bin = "011001001101100100110110010011011001001101100100110110010011";
                                            final String expected = new BigInteger(bin, 2).toString();
                                            final String actual = dec(bin);
                                            System.out.println("Expected: " + expected);
                                            System.out.println("Decimal Representation: " + actual);
                                            assert expected.equals(actual);
                                       }
                                  
                                       private static String dec(String str) {
                                            String decString = "";
                                            int count = 0, count2 = 0, biggest = 0, num = 0, carry = 0, index = 0, sum = 0, place = 0, start = 0, length = 1;
                                            int[] binary, power, toBeAdded;
                                  
                                            binary = new int[str.length()];
                                            power = new int[str.length()];
                                  
                                            for (int i = 0; i < str.length(); i++)
                                                 binary[i] = Integer.parseInt(Character.toString(str.charAt(i)));
                                            for (int i = str.length() - 1; i >= 0; i--) 
                                            {
                                                 power[i] = (int) Math.pow(2.0, index);
                                                 index++;
                                            }
                                  
                                            for (int i = 0; i < binary.length; i++)
                                                 if (binary[i] == 1)
                                                      count++;
                                            toBeAdded = new int[count];
                                  
                                            for (int i = binary.length - 1; i >= 0; i--)
                                                 if (binary[i] == 1) {
                                                      toBeAdded[count2] = power;
                                                      count2++;
                                                 }
                                            biggest = Integer.toString(toBeAdded[toBeAdded.length - 1]).length();
                                            for (int i = biggest; i > 0; i--)
                                            {
                                                 for (int j = start; j < toBeAdded.length; j++) {
                                                      num = Integer.parseInt(Character.toString(Integer.toString(
                                                                toBeAdded[j]).charAt(
                                                                Integer.toString(toBeAdded[j]).length() - 1 + place)));
                                                      sum += num;
                                                 }
                                                 sum += carry;
                                                 if (sum > 9) {
                                                      carry = Integer.parseInt(Integer.toString(sum).substring(0,
                                                                Integer.toString(num).length()));
                                                      decString += Integer.toString(sum).charAt(
                                                                Integer.toString(sum).length() - 1);
                                                 } else {
                                                      carry = 0;
                                                      decString += Integer.toString(sum).charAt(
                                                                Integer.toString(sum).length() - 1);
                                                 }
                                                 sum = 0;
                                                 place--;
                                                 for (int k = 0; k < toBeAdded.length; k++)
                                                      if (Integer.toString(toBeAdded[k]).length() > length) {
                                                           length = Integer.toString(toBeAdded[k]).length();
                                                           start = k;
                                                           break;
                                                      }
                                            }
                                            return reverse(decString);
                                       }

                                       private static String reverse(String str) {
                                            String rev = "";

                                            for (int i = str.length() - 1; i >= 0; i--)
                                                 rev += str.charAt(i);
                                            return rev;
                                       }
                                  }

                                  ~
                                  • 14. Re: How long can a string be?
                                    807588
                                    And the crux of the problem is here:
                                              for (int i = str.length() - 1; i >= 0; i--) 
                                              {
                                                   power[i] = (int) Math.pow(2.0, index);
                                                   index++;
                                              }
                                    You've got a string 60 characters long, and you're trying to come up with int values up to 2**60. The maximum value of an int is far smaller than that. Have a look at the definitions for Java's primitive data types and you'll need to rethink how you're going about converting binary to decimal.

                                    Hope this helps get you on the right path!

                                    ~