Newsgroups: comp.ai.genetic
Path: cantaloupe.srv.cs.cmu.edu!rochester!udel!news.mathworks.com!news.alpha.net!uwm.edu!cs.utexas.edu!swrinde!pipex!uknet!bailgate!roborough.gpsemi.com!whipp
From: whipp@roborough.gpsemi.com (David Whipp)
Subject: Re: GRAY CODE
Message-ID: <D45FIF.A3E@lincoln.gpsemi.com>
Sender: usenet@lincoln.gpsemi.com (usnet account)
Nntp-Posting-Host: psupw22.roborough.gpsemi.com
Organization: GEC Plessey Semiconductors
References: <3h7052INNrf6@ringer.syd.dwt.CSIRO.AU> <3h8af0$2j8@newsbf02.news.aol.com>
Date: Fri, 17 Feb 1995 14:42:14 GMT
Lines: 39

> In article <3h6geq$ar9@network.ucsd.edu> acangelo@ucsd.edu (Angelo
> Cangelosi) writes:
> Hello,
>
> I am looking for the algorithm to convert the binary code to the gray
> code and viceversa.
> I am making simulation of GA and neural networks and I would like to use
> the gray coding.
>
> Does anybody know a ftp site where to get a C source code to do this or
> a book or article where I can find the algorithm?
>
> Thanks a lot.

#include <limits.h>
typedef unsigned int type_t;
#define bits_in_word CHAR_BIT * sizeof(type_t);

/* type_t is whatever type you use to store your values; probably     */
/* unsigned int or unsigned long */

type_t binary_to_gray(type_t value) {
	return value ^ (value >> 1);
}

type_t gray_to_binary(type_t value) {
	type_t mask;
	for(mask=1<<(bits_in_word-1) ; mask>1 ; mask = mask>>1) {
		value ^= (value & mask) >> 1;
	}
	return value;
}


-- 
                    David P. Whipp.            <whipp@roborough.gpsemi.com>
Not speaking for:   -------------------------------------------------------
 G.E.C. Plessey     Due to transcription and transmission errors, the views
 Semiconductors     expressed here may not reflect even  my  own  opinions!
