Answers for "java binary addition"

1

addition of two binary numbers in java

import java.util.Scanner;
public class JavaExample {
   public static void main(String[] args)
   {	 
	long b1, b2;
	int i = 0, carry = 0;
	int[] sum = new int[10];
	Scanner scanner = new Scanner(System.in);
	System.out.print("Enter first binary number: ");
	b1 = scanner.nextLong();
	System.out.print("Enter second binary number: ");
	b2 = scanner.nextLong();
	scanner.close();
	while (b1 != 0 || b2 != 0) 
	{
		sum[i++] = (int)((b1 % 10 + b2 % 10 + carry) % 2);
		carry = (int)((b1 % 10 + b2 % 10 + carry) / 2);
		b1 = b1 / 10;
		b2 = b2 / 10;
	}
	if (carry != 0) {
		sum[i++] = carry;
	}
	--i;
	System.out.print("Output: ");
	while (i >= 0) {
		System.out.print(sum[i--]);
	}
	System.out.print("\n");  
   }
}
Posted by: Guest on August-16-2020
0

java binary addition

public static String addBinary(){
 // The two input Strings, containing the binary representation of the two values:
    String input0 = "1010";
    String input1 = "10";

    // Use as radix 2 because it's binary    
    int number0 = Integer.parseInt(input0, 2);
    int number1 = Integer.parseInt(input1, 2);

    int sum = number0 + number1;
    return Integer.toBinaryString(sum); //returns the answer as a binary value;
}
Posted by: Guest on April-01-2021

Code answers related to "java binary addition"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language