In this Java tutorial, we will convert the given string of 0's and 1's from binary to gray code and vice versa
Introduction:
Let's first understand what does a gray code means, A Gray code is also referred to as cyclic code (or) reflected binary code (or) unit distant code(such that two successive values differ in only one bit).
Decimal Binary code Gray code
0 000 000
1 001 001
2 010 011
3 011 010
4 100 110
5 101 111
6 110 101
7 111 100
Example:
a) Let the binary code be 101 then Gray code representation is given by 111.
Binary code: 1 (+) 0 (+) 1 (XOR operation between i th and (i-1)th bit other than the MSB )
| \ \
Gray code: 1 1 1 (whereas MSB is written as it is )
where (+) is XOR operation (odd number of 1 detector)
Truth table of XOR operation is
a b a(+)b
0 0 0
0 1 1
1 0 1
1 1 0
b) Let the Gray code be 111 then Binary code representation is given by 101.
Gray code: 1 1 1 (XOR operation between i th bit of gray code and (i-1)th bit of binary code other than the MSB)
| (+) /(+) /
Binary code: 1 0 1 (whereas MSB is written as it is )
where (+) is XOR operation (odd number of 1 detector)
import java.util.Scanner; public class CodeConverter { public static void main(String[] args) { Scanner in= new Scanner(System.in); System.out.println("Enter the input code which is binary string of 0's and 1's"); String input=in.next(); System.out.println("Choose in any one option \t1.Binary to Gray\t2.Gray to Binary"); int option=in.nextInt(); if(option==1){ System.out.println("Gray code representation of given binary code is "+ B_to_G(input)); } else{ System.out.println("Binary code representation of given gray code is "+ G_to_B(input)); } } public static String B_to_G(String input){ char[] code=input.toCharArray(); char[] out=new char[code.length]; for (int i = 0; i }
Output:
Enter the input code which is a binary string of 0's and 1's 1001
Choose in any one option 1.Binary to Gray 2.Gray to Binary
1
Gray code representation of given binary code is 1101
Enter the input code which is a binary string of 0's and 1's 1111
Choose in any one option 1.Binary to Gray 2.Gray to Binary
2
Gray code representation of given binary code is 1010
Submitted by Matam Deekshith (deekshithmatam)
Download packets of source code on Coders Packet
Comments