import java.util.Random; public class ECUtilities { public static int binary2gray(int n){ // n has 32 bits: n(31), n(30),..., n(1), n(0) int result,br,bl; br = (n & 0x80000000) == 0? 0:1; // br: the most significant bit of n, it is n(31) // bl: is the second most significant bit of n, it is n(30) result = br; for(int i=0; i < 31; i++){ n <<= 1; bl = (n & 0x80000000) == 0? 0:1; result <<= 1; result |= (br^bl); br = bl; } return result; } public static int gray2binary(int a){ int lb = (a & 0x80000000) == 0? 0:1; int result = lb; for(int i=0; i < 31; i++){ a <<= 1; lb = lb ^ ((a & 0x80000000) == 0? 0:1); result <<= 1; result |= lb; } return result; } public static String binaryString(int n,int size){ // convert n to its binary equvalent in a String of length "size" // for example binaryString(3,4) returns "0011" // and binaryString(3,8) returns "00000011" if( size < 1 || size > 32 ) System.err.println("error: bad argument for binaryString"); String result = ""; for(int i=0; i < size; i++){ result = ((n & 1) == 0? 0:1) + result; n >>= 1; } return result; } public static void main(String[] args) { } }