Advertisement
Shailrshah

Checksum for sending data

Jan 23rd, 2014
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.10 KB | None | 0 0
  1. import java.util.Scanner;
  2. class BinaryAdd{
  3.     static String complement(String str){
  4.         String s1 = "";
  5.         for(int i = 0; i < 8; i++)
  6.             if(str.charAt(i) == '1') s1 += "0";
  7.             else s1 += "1";
  8.         return s1;
  9.     }
  10.     static String appendZeros(String str){
  11.         for(int i = 8 - str.length(); i != 0; i--) str = "0" + str;
  12.         return str;
  13.     }
  14.     public static void main(String args[]){
  15.         Scanner sc = new Scanner(System.in);
  16.         System.out.println("Enter an 16-bit binary number: ");
  17.         String data = sc.next();    
  18.         int n1 = Integer.parseInt(data.substring(0,8), 2);
  19.         int n2 = Integer.parseInt(data.substring(8), 2);
  20.         String sum = appendZeros(Integer.toBinaryString(n1 + n2));
  21.         String toSend = data + complement(sum);
  22.         System.out.println(toSend +" is being sent(data+checksum).");
  23.         n1 = Integer.parseInt(toSend.substring(0,8), 2);
  24.         n2 = Integer.parseInt(toSend.substring(8, 16), 2);
  25.         int n3 = Integer.parseInt(toSend.substring(16), 2);
  26.         sum = appendZeros(Integer.toBinaryString(n1 + n2 + n3));
  27.         if(complement(sum).equals("00000000")) System.out.println("Success.");
  28.         else System.out.println("Failed.");
  29.     }
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement