添加,减法,除法和乘以存储在布尔数组中的两个二进制数

时间:2018-03-01 04:14:09

标签: java binary

我需要帮助制作二进制计算器。我试图添加,减去,除法和乘以两个二进制数,这些二进制数在java中存储为boolean []数组。我很困难,所以一些帮助将不胜感激!谢谢!

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;
}

1 个答案:

答案 0 :(得分:0)

首先转换为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;
}

然后,muliply / add / divide / subtract,然后,转换回布尔数组:

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;
}