Advertisement
SVXX

Gray Code Checker

Feb 25th, 2014
416
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.16 KB | None | 0 0
  1. package miscellaneous;
  2. import java.util.Scanner;
  3.  
  4. public class GrayCodeMain
  5. {
  6.     public static void main(String... args)
  7.     {
  8.         String a = "", b = "";
  9.         Scanner scan = new Scanner(System.in);
  10.         System.out.print("Enter the first 8-bit number: ");
  11.         a = scan.next();
  12.         System.out.print("\nEnter the second 8-bit number: ");
  13.         if(scan.hasNext())
  14.             b = scan.next();
  15.         System.out.print("\nIs one the Gray code of the other?: ");
  16.         if(GrayCode.checkGray(a, b))
  17.             System.out.print("Yes.");
  18.         else
  19.             System.out.print("No.");
  20.     }
  21. }
  22.  
  23. class GrayCode
  24. {
  25.     static boolean checkGray(String a, String b)
  26.     {
  27.         long first = Long.parseLong(a, 2);
  28.         long second = Long.parseLong(b, 2);
  29.        
  30.         long encode_1 = encode(first);
  31.         long encode_2 = encode(second);
  32.         long decode_1 = decode(first);
  33.         long decode_2 = decode(second);
  34.        
  35.         if((encode_1 == second) || (encode_2 == first))
  36.             return true;
  37.         if((decode_1 == second) || (decode_2 == first))
  38.             return true;
  39.        
  40.         return false;
  41.     }
  42.    
  43.     static long encode(long n)
  44.     {
  45.         long p = n ^ (n >>> 1);
  46.         return p;
  47.     }
  48.    
  49.     static long decode(long n)
  50.     {
  51.         long p = n;
  52.         while((n >>> 1) != 0)
  53.             p ^= n;
  54.         return p;
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement