Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- class BinaryAdd{
- static String complement(String str){
- String s1 = "";
- for(int i = 0; i < 8; i++)
- if(str.charAt(i) == '1') s1 += "0";
- else s1 += "1";
- return s1;
- }
- static String appendZeros(String str){
- for(int i = 8 - str.length(); i != 0; i--) str = "0" + str;
- return str;
- }
- public static void main(String args[]){
- Scanner sc = new Scanner(System.in);
- System.out.println("Enter an 16-bit binary number: ");
- String data = sc.next();
- int n1 = Integer.parseInt(data.substring(0,8), 2);
- int n2 = Integer.parseInt(data.substring(8), 2);
- String sum = appendZeros(Integer.toBinaryString(n1 + n2));
- String toSend = data + complement(sum);
- System.out.println(toSend +" is being sent(data+checksum).");
- n1 = Integer.parseInt(toSend.substring(0,8), 2);
- n2 = Integer.parseInt(toSend.substring(8, 16), 2);
- int n3 = Integer.parseInt(toSend.substring(16), 2);
- sum = appendZeros(Integer.toBinaryString(n1 + n2 + n3));
- if(complement(sum).equals("00000000")) System.out.println("Success.");
- else System.out.println("Failed.");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement