Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import static java.lang.System.*;
- import java.util.Scanner;
- import java.lang.Math;
- class Main
- {
- public static int[] convertToBinary(int x){
- int y [] = {0,0,0,0,0,0,0,0};
- if(x >= 512) {
- x = x - 512; //Overflowed
- Main.didOverflow = true;
- }
- if(x >= 256) {
- y [] = new int[8];
- x = x - 256; //0
- Main.didOverflow = true;
- y[8] = 1;
- }
- if(x >= 128){
- x = x - 128;
- y[7] = 1;
- }else{
- y[7] = 0;
- }
- if(x >= 64){
- x = x - 64;
- y[6] = 1;
- }else{
- y[6] = 0;
- }
- if(x >= 32){
- x = x - 32;
- y[5] = 1;
- }else{
- y[5] = 0;
- }
- if(x >= 16){
- x = x - 16;
- y[4] = 1;
- }else{
- y[4] = 0;
- }
- if(x >= 8){
- x = x - 8;
- y[3] = 1;
- }else{
- y[3] = 0;
- }
- if(x >= 4){
- x = x - 4;
- y[2] = 1;
- }else{
- y[2] = 0;
- }
- if(x >= 2){
- x = x - 2;
- y[1] = 1;
- }else{
- y[1] = 0;
- }
- if(x >= 1){
- x = x - 1;
- y[0] = 1;
- }else{
- y[0] = 0;
- }
- if(Main.didOverflow)
- {
- int[] tmp = y.clone();
- int pos = 8;
- for(int i = 0; i < y.length;i++)
- {
- y[pos] = tmp[i];
- pos++;
- }
- }
- return y;
- }
- public static boolean didOverflow = false;
- public static int c;
- public static int d;
- public static int[] addBin(int[] arr1, int[] arr2)
- {
- int[] arr3 = new int[8];
- int sum = Main.c + Main.d;
- Main.didOverflow = false;
- arr3 = convertToBinary(sum);
- return arr3;
- }
- public static void printBin(int[] addedArray){
- System.out.println("\n\nAdded:");
- if(Main.didOverflow){
- System.out.println("Error: overflow");
- for(int i = 0; i < 8 1;i++)
- System.out.print(addedArray[i]+ " ");
- } else {
- for(int i = 7; i >= 0;i--)
- System.out.print(addedArray[i]+ " ");
- }
- }
- public static void main(String[] args) throws IOException {
- Scanner scan = new Scanner(System.in);
- System.out.println("Enter a base ten number between 0 and 255, inclusive.");
- c = scan.nextInt();
- System.out.println("Enter a base ten number between 0 and 255, inclusive.");
- d = scan.nextInt();
- int[] arr1 = new int[8];
- int[] arr2 = new int[8];
- int[] arr3 = new int[8];
- arr1 = convertToBinary(c);
- arr2 = convertToBinary(d);
- System.out.println("First binary number:");
- for(int i = 7; i >= 0;i--){
- System.out.print(arr1[i]+ " ");
- }
- System.out.println("\n\nSecond binary number:");
- for(int i = 7; i >= 0;i--){
- System.out.print(arr2[i]+ " ");
- }
- arr3 = addBin(arr1,arr2);
- printBin(arr3);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement