简体   繁体   中英

Adding, Subtracting, Dividing, and Multiplying two binary numbers stored in boolean arrays

I need help with making a Binary calculator. I am trying to add, subtract, divide, and multiply two binary numbers that are stored as a boolean[] array in java. I'm pretty stuck so some help would be greatly appreciated! thanks!

private static boolean[] multiply(boolean[] bits1, boolean[] bits2) {
    // TODO Auto-generated method stub
    return null;
}

private static boolean[] subtract(boolean[] bits1, boolean[] bits2) {
    // TODO Auto-generated method stub
    return null;
}

private static boolean[] add(boolean[] bits1, boolean[] bits2) {

    return null;
}
private static Object[] divide(boolean[] bits1, boolean[] bits2) {
    // TODO Auto-generated method stub
    return null;
}

First convert to a long:

long boolToLong(boolean[] b){
   long sum = 0;
   for(int i = 0; i < b.length; i++){
      if(b[i])sum += Math.pow(2, i);
   }
   return sum;
}

Then, muliply/add/divide/subtract, Then, convert back to a boolean array:

boolean[] longToBool(long l){
   boolean[] result = new boolean[1+(int) Math.ceil(Math.log(l)/Math.log(2))];
   for(int i = 0; i < result.length; i++){
      result[i] = ((l%(Math.pow(2, i+1))) >= Math.pow(2, i))
   }
   return result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM