Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class Main {
- public static int[] convertToBinary(int b) {
- int[] binArray = {0,0,0,0,0,0,0,0};
- for (int i = 7; i >= 1; i--) {
- if (b >= Math.pow(2, i)) {
- binArray[7 - i]++;
- b = b - (int)Math.pow(2, i);
- }
- }
- return binArray;
- }
- public static void printBin(int b[]) {
- for (int i = 0; i < b.length; i++) {
- System.out.print(b[i] + " ");
- }
- }
- public static int[] addBin(int a[], int b[]) {
- int c = 0;
- int d = 0;
- for (int i = 1; i < a.length; i++) {
- if (a[i] == 1) {
- c = c + (2 ^ i);
- }
- }
- for (int i = 1; i < b.length; i++) {
- if (b[i] == 1) {
- d = d + (2 ^ i);
- }
- }
- int sum = c + d;
- return (convertToBinary(sum));
- }
- public static void main(String args[]) {
- Scanner scan = new Scanner(System. in );
- System.out.println("Enter a base ten number between 0 and 255, inclusive.");
- int num = scan.nextInt();
- System.out.println("Enter a base ten number between 0 and 255, inclusive.");
- int num2 = scan.nextInt();
- System.out.println("First binary number:");
- int[] bin = convertToBinary(num);
- printBin(bin);
- System.out.println("Second binary number:");
- printBin(convertToBinary(num2));
- System.out.println("Added:");
- printBin(addBin(convertToBinary(num), convertToBinary(num2)));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement