10 Replies Latest reply: Jan 30, 2010 6:23 AM by 843789 RSS

    Is this code terribly written to work out a binary number

    843789
      <Library function not allowed to be used !>

      The reason i ask is, i am starting a placement year next year, and i have a job with the biggest pharmaceutical firm in the world, as a jr. java developer. If my coding sucks that bad then i am going to quit before i get sacked. Just to let you know, i appreciate the variable names and while loop could have been better, those 2 things are just a direct result of the 2 minute knock together.
      public void binary(int number)
          {
              ArrayList<Integer> arrayOfBinary = new ArrayList<Integer>();
              
              float theNumber = number;
              
              int i = 0;
              
              while(true){
                  theNumber = theNumber / 2;
                  if(theNumber % 1 != 0){
                      arrayOfBinary.add(1);
                      theNumber = theNumber - 0.5f;
                      i++;
                  }
                  else{
                      arrayOfBinary.add(0);
                      i++;
                  }
                  if(theNumber == 0){
                      break;
                  }            
              }
              
              print(arrayOfBinary);
          }
          
          public void print(ArrayList<Integer>list)
          {
              Collections.reverse(list);
      
              for(int i = 0; i < list.size(); i++){
                  System.out.print(list.get(i));
              }
          }
      Don't worry about holding back, i guess its time i new the truth so i can save the organisation from hiring me :(

      Edited by: compSciUndergrad on Jan 30, 2010 2:14 AM
        • 1. Re: Is this code terribly written to work out a binary number
          699554
          Heres my version of your program.
          public void printBinary(int number) {
            System.out.println(Integer.toBinaryString(number));
          }
          Mel
          • 2. Re: Is this code terribly written to work out a binary number
            843789
            i did say not to use the library fnction

            cheat! ;)
            • 3. Re: Is this code terribly written to work out a binary number
              699554
              compSciUndergrad wrote:
              i did say not to use the library fnction

              cheat! ;)
              Oh my bad
              • 4. Re: Is this code terribly written to work out a binary number
                699554
                My non cheating version. Returns the binary String representation of both positive and negative decimal numbers.
                public class Foo {
                     public static void main(String[] args) {
                          int num = -3;
                          System.out.println(decimalToBinaryString(num));
                     }
                     
                     public static String decimalToBinaryString(final int number) {
                          StringBuilder binary = new StringBuilder();
                          int decimal = number;
                          while(decimal != 0) {
                               binary.append(decimal % 2 == 0 ? '0' : '1');
                               decimal /= 2;
                          }
                          return number > 0 ? binary.reverse().toString() : twosComplement(binary.reverse().toString());
                     }
                     
                     public static String twosComplement(final String binary) {
                          StringBuilder complement = new StringBuilder();
                          for(char c : binary.toCharArray()) {
                               complement.append(c == '0' ? '1' : '0');
                          }
                          StringBuilder twosComplement = new StringBuilder();
                          int i;
                          for(i = complement.length() - 1; i >= 0; i--) {
                               if(complement.charAt(i) == '1') {
                                    twosComplement.append('0');
                               } else {
                                    twosComplement.append('1');
                                    break;
                               }
                          }
                          //Set i greater or equal to 0
                          i = i < 0 ? 0 : i;
                          return "1" + complement.substring(0, i) + twosComplement.reverse().toString();
                     }
                }
                Mel
                • 5. Re: Is this code terribly written to work out a binary number
                  699554
                  Anyway back to you. Here are my nitpicks from a fellow student.
                  public void binary(int number)
                  The method "binary" comprises of two major functions, first function converts a decimal number into a binary number. The second function calls a further function to print the binary number, but first it has to reverse the String. The end result is that the decimal-to-binary conversion method you have created becomes redundant if I do not wish to print the resulting binary String. What a waste!
                  ArrayList<Integer> arrayOfBinary = new ArrayList<Integer>();
                  arrayOfBinary could become redundant due to the declared type if arrayOfBinary were to be initialized with another List. The alternative is:
                  List<Integer> arrayOfBinary = new ArrayList<Integer>();
                   int i = 0;
                  i does absolutely nothing during it's life time apart from being incremented.
                  theNumber = theNumber - 0.5f;
                  What is 0.5f?
                   print(arrayOfBinary);
                  Does not belong in this method.
                   public void print(ArrayList<Integer>list)
                  Type constricts parameter to ArrayLists and not Lists
                   Collections.reverse(list);
                  This should be part of the algorithm to convert a decimal number to a binary String. The algorithm should not continue in a print method.
                   for(int i = 0; i < list.size(); i++){
                    System.out.print(list.get(i));
                   }
                  Would be more conventional to return a String, rather then printing the output.

                  Mel
                  • 6. Re: Is this code terribly written to work out a binary number
                    843789
                    Thanks mel for the really informative response

                    The i really was pointless but i did have a valid reason for this, i promise! I was going to use a normal array and then use the i to add the element to the i'th position. However the rush i was in lead for me to ditch the array and opt for an array list, however i forgot to take the index i out :D

                    I will definatley take all of these points on board when revising this version when i have more time later

                    thanks once again
                    • 7. Re: Is this code terribly written to work out a binary number
                      843789
                      compSciUndergrad wrote:
                      i did say not to use the library fnction
                      I'd return any requirements document with such an irrate statement with a note that I won't have anything to do with its implementation.
                      • 8. Re: Is this code terribly written to work out a binary number
                        843789
                        jwenting wrote:
                        compSciUndergrad wrote:
                        i did say not to use the librjavascript:void(0);ary fnction
                        I'd return any requirements document with such an irrate statement with a note that I won't have anything to do with its implementation.
                        i see what your saying

                        the reason i said that though was because i new i could code it in one line using the library function, but the idea was to code something that showed how i would try and do something

                        rushing it didn't give a full perspective of how i would code so maybe this thread is a little pointless in the end, though the feedback from mel has defiantly given some great pointers.

                        When i come to do my placement i will for sure use library methods in all places possible, they have been tested extensively so why shouldn't i, i suppose

                        thanks again
                        • 9. Re: Is this code terribly written to work out a binary number
                          843789
                          , but the idea was to code something that showed how i would try and do something
                          Then explain how you came up with these two lines?

                          if(theNumber % 1 != 0){

                          and

                          theNumber = theNumber - 0.5f;
                          • 10. Re: Is this code terribly written to work out a binary number
                            843789
                            Returns the binary String representation of both positive and negative decimal numbers.
                            Well, if you're going to print a bit-sequence you don't have to take into account how this sequence is interpreted at a higher level (whether it's considered positive or negative really doesn't matter). You simply print the bits.

                            So why not just sample the 32 bits from left to right and print them.

                            Printing bits merits an efficient bit-level solution in my view. And Java supports that, like this
                            public static void binary2(int number) {
                                 boolean b=false;
                                 int p = 1<<31;
                                 for (int i=0; i<32; i++) {
                                      char c = ((number & p) == 0) ? '0' : '1';
                                      b |= c=='1';
                                      if (b) System.out.print(c);
                                      p >>>= 1;
                                 }
                            }
                            The b variable is used to skip leading 0's.

                            Instead of printing you can of course compose a String or whatever.