Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class SumaAssembly{
- public static void main (String args[]) {
- Scanner input = new Scanner(System.in);
- System.out.print("Ingrese un numero: ");
- int var_A = input.nextInt();
- System.out.print("Ingrese un numero a sumar con " + var_A + ": ");
- int var_B = input.nextInt();
- String bin_A = Integer.toBinaryString(var_A);
- String bin_B = Integer.toBinaryString(var_B);
- String bin_Result = "";
- //Normaliza el largo de ambos binarios.
- while (bin_A.length() > bin_B.length()){
- bin_B = "0" + bin_B;
- }
- while (bin_A.length() < bin_B.length()){
- bin_A = "0" + bin_A;
- }
- bin_A = "0" + bin_A;
- bin_B = "0" + bin_B;
- //Largo de los binarios.
- int binary_length = bin_A.length();
- System.out.println("Los numeros ingresados son en binario " + bin_A + " y " + bin_B + " respectivamente.");
- System.out.println("Calculando su suma...");
- boolean bol_A;
- boolean bol_B;
- boolean bol_C = false;
- boolean bol_S;
- for(int i = binary_length -1; i >= 0; i--){
- //Obtiene el valor del String en la posicion i.
- bol_A = charToBool(bin_A.charAt(i));
- bol_B = charToBool(bin_B.charAt(i));
- //Calcula S y C.
- bol_S = calculate_S(bol_A, bol_B, bol_C);
- bol_C = calculate_C(bol_A, bol_B, bol_C);
- //System.out.println("A: " + boolToChar(bol_A) + " B: " + boolToChar(bol_B) + " S: " + boolToChar(bol_S) + " C: " + boolToChar(bol_C));
- //Agrega el resultado S al String que almacena el resultado.
- bin_Result = boolToChar(bol_S) + bin_Result;
- }
- //Convierte el binario en String a decimal.
- int var_Result = Integer.parseInt(bin_Result, 2);
- System.out.println("EL resultado en binario es " + bin_Result + " lo cual corresponde al numero " + var_Result + ".");
- }
- public static boolean calculate_S(boolean bi_A, boolean bi_B, boolean bi_Ci){
- boolean result;
- result = bi_A ^ bi_B;
- result = result ^ bi_Ci;
- return result;
- }
- public static boolean calculate_C(boolean bi_A, boolean bi_B, boolean bi_Ci){
- boolean xor_result;
- boolean result;
- xor_result = bi_A ^ bi_B;
- xor_result = !(xor_result && bi_Ci);
- result = !(bi_A && bi_B);
- result = !(xor_result && result);
- return result;
- }
- public static boolean charToBool(char input){
- if (input == '0'){
- return false;
- }
- return true;
- }
- public static char boolToChar(boolean input){
- if(input){
- return '1';
- }
- return '0';
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement