HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMajor

Binary difference checker

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
differencebinarychecker

Problem

My code needs to take two ints and then check those ints to see if their binary representations have any differences. The function convertBits returns the number of differences between the two binary forms of the ints.

For example, you can change 31 to 14 by flipping the 4th and 0th bit:

31:  0 0 0 1 1 1 1 1
14:  0 0 0 0 1 1 1 0
---  ---------------
bit  7 6 5 4 3 2 1 0


Thus 31 and 14 should return 2.

My code works, but it is failing the time test. In short, it needs to be more efficient. I welcome any suggestions as to how to do this.

import java.util.ArrayList;

    public class BinaryChecker {
        public static void main(String[] args){
             b call = new b();
             System.out.println(call.convertBits(31, 14));
        }

     public static int convertBits(int a, int b){
         int counter = 0;

         String A = Integer.toBinaryString(a);
         String B = Integer.toBinaryString(b);

         System.out.println("The binary value of " + a + " " + "is " +   A +"." + "The binary value of " + b + " " + "is " + B);
         //add to arraylist 1 and 2

         ArrayList String1 = new ArrayList();

         ArrayList String2 = new ArrayList();
         int size = 0;

         for(int i = 0; i < A.length(); i++){
             char Aa = A.charAt(i);
             String1.add(Aa);
         }
         for(int x = 0; x < B.length(); x++){
             char Bb = B.charAt(x);
             String2.add(Bb);
         }
         //check if String1 is 8 chars long and add 0 to beginning if not
         while (String1.size() != 8){
             String1.add(0, '0');
         }
         while (String2.size() != 8){
             String2.add(0, '0');
         }

         for (int i =0; i < String1.size(); i++){
             char biteA = String1.get(i);
             char biteB = String2.get(i);
             if(biteA != biteB){
                 counter++;
             }
         }

         return counter;
     }
}

Solution

There's no need to roll your own: the library support is there.

public static int convertBits(int a, int b) {
    return Integer.bitCount(a ^ b);
}


For what it's worth, I don't think convertBits is a very descriptive name for the method. I'd suggest something like countBitDifferences.

Code Snippets

public static int convertBits(int a, int b) {
    return Integer.bitCount(a ^ b);
}

Context

StackExchange Code Review Q#134037, answer score: 32

Revisions (0)

No revisions yet.