Advertisement
Guest User

Untitled

a guest
Feb 8th, 2016
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.52 KB | None | 0 0
  1. import java.io.*;
  2. import static java.lang.System.*;
  3. import java.util.Scanner;
  4. import java.lang.Math;
  5.  
  6. class Main
  7. {
  8. public static int[] convertToBinary(int x){
  9. int y [] = {0,0,0,0,0,0,0,0};
  10. if(x >= 512) {
  11. x = x - 512; //Overflowed
  12. Main.didOverflow = true;
  13. }
  14. if(x >= 256) {
  15. x = x - 256; //0
  16. Main.didOverflow = true;
  17. }
  18. if(x >= 128){
  19. x = x - 128;
  20. y[7] = 1;
  21. }else{
  22. y[7] = 0;
  23. }
  24. if(x >= 64){
  25. x = x - 64;
  26. y[6] = 1;
  27. }else{
  28. y[6] = 0;
  29. }
  30. if(x >= 32){
  31. x = x - 32;
  32. y[5] = 1;
  33. }else{
  34. y[5] = 0;
  35. }
  36. if(x >= 16){
  37. x = x - 16;
  38. y[4] = 1;
  39. }else{
  40. y[4] = 0;
  41. }
  42. if(x >= 8){
  43. x = x - 8;
  44. y[3] = 1;
  45. }else{
  46. y[3] = 0;
  47. }
  48. if(x >= 4){
  49. x = x - 4;
  50. y[2] = 1;
  51. }else{
  52. y[2] = 0;
  53. }
  54. if(x >= 2){
  55. x = x - 2;
  56. y[1] = 1;
  57. }else{
  58. y[1] = 0;
  59. }
  60. if(x >= 1){
  61. x = x - 1;
  62. y[0] = 1;
  63. }else{
  64. y[0] = 0;
  65. }
  66. return y;
  67. }
  68. public static boolean didOverflow = false;
  69. public static int c;
  70. public static int d;
  71.  
  72. public static int[] addBin(int[] arr1, int[] arr2)
  73. {
  74. int[] arr3 = new int[8];
  75. int sum = Main.c + Main.d;
  76. Main.didOverflow = false;
  77. arr3 = convertToBinary(sum);
  78.  
  79. return arr3;
  80. }
  81.  
  82.  
  83.  
  84. public static void printBin(int[] addedArray){
  85.  
  86.  
  87. System.out.println("\n\nAdded:");
  88. if(Main.didOverflow){
  89. System.out.println("Error: overflow");
  90. }
  91. for(int i = 7; i >= 0;i--){
  92. System.out.print(addedArray[i]+ " ");
  93. }
  94.  
  95.  
  96.  
  97. }
  98.  
  99. public static void main(String[] args) throws IOException {
  100. Scanner scan = new Scanner(System.in);
  101.  
  102. System.out.println("Enter a base ten number between 0 and 255, inclusive.");
  103. c = scan.nextInt();
  104.  
  105. System.out.println("Enter a base ten number between 0 and 255, inclusive.");
  106. d = scan.nextInt();
  107.  
  108. int[] arr1 = new int[8];
  109. int[] arr2 = new int[8];
  110. int[] arr3 = new int[8];
  111.  
  112. arr1 = convertToBinary(c);
  113. arr2 = convertToBinary(d);
  114.  
  115. System.out.println("First binary number:");
  116. for(int i = 7; i >= 0;i--){
  117. System.out.print(arr1[i]+ " ");
  118. }
  119.  
  120. System.out.println("\n\nSecond binary number:");
  121. for(int i = 7; i >= 0;i--){
  122. System.out.print(arr2[i]+ " ");
  123. }
  124.  
  125. arr3 = addBin(arr1,arr2);
  126. printBin(arr3);
  127.  
  128. }
  129. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement