! This file: http://ftp.aset.psu.edu/pub/ger/fortran/hdk/gray2bin.f90 ! ! gray2bin and bin2gray by sk8terg1rl, Mike Metcalf, and Beliavsky as ! posted in comp.lang.fortran on 7 & 8 May 2007. ! ! Some wisdom from Mike and Beliavsky: ! ! "This is just a small program, but in the real world one tries to ! program in such a way as to avoid as many sources of error as ! possible. One of the main sources in traditional Fortran is getting ! the interface between two procedures wrong. Putting procedures into ! a module makes interface checking at compile time possible. Giving ! arguments intent ensures they are actually used in the way intended ! (think about modifying a 100,000 line program in five years' time). ! Assumed-shape arrays avoid you having to pass explicit length ! information (the compiler will always get this right; the programmer ! will sometimes get it wrong). The other suggestions, about private, ! implicit none, all go in the same direction of 'defensive ! programming'. Mike Metcalf ! ! ! "Let me say that some of the features of Fortran 90 *do* increase ! the amount of code that needs to be written to do a particular ! calculation. Those features can justify themselves in larger ! programs because more errors are caught at compile time and run time ! and because code can be easier to understand." Beliavsky ! ! ! Also see: http://www.faqs.org/faqs/ai-faq/genetic/part6/section-1.html ! from comp.ai.genetic.and: http://www.pc-control.co.uk/gray_code.htm ! Gray codes were patented in 1953 by Frank Gray, a Bell Labs ! researcher. ! module convert implicit none private public :: binary_to_gray,gray_to_binary contains Subroutine binary_to_gray(binary, gray) Integer, intent(in):: binary(:) ! (length) Integer, intent(out):: gray(:) ! (length) Integer :: length, i length = size(binary) if (size(gray) /= length) then write (*,*) & "in convert::binary_to_gray, size(binary), size(length) =", & length,size(gray)," must be equal, STOPPING" stop end if gray(length) = binary(length) do i = 1, length-1 gray(i) = ieor(binary(i), binary(i+1)) enddo End subroutine binary_to_gray Subroutine gray_to_binary(binary, gray) Integer, intent(out):: binary(:) Integer, intent(in):: gray(:) Integer :: length, temp_bit, i length = size(gray) if (size(binary) /= length) then write (*,*) & "in convert::gray_to_binary, size(gray), size(length) =",& length,size(binary)," must be equal, STOPPING" stop end if binary(length) = gray(length) i = length - 1 do i = length - 1, 1, -1 temp_bit = binary(i+1) temp_bit = ieor(temp_bit, gray(i)) binary(i) = temp_bit enddo End subroutine gray_to_binary end module convert Program graytest Use convert Implicit None Integer:: length Integer, allocatable:: binary(:), gray(:) length = 4 Allocate (binary(length)) Allocate (gray(length)) gray(1:3) = 0 gray(4) = 1 Call gray_to_binary(binary,gray) Write (*,'(a10,100i3)') 'Binary =',binary(1:length) Write (*,'(a10,100i3)') 'Gray =',gray(1:length) Deallocate(binary,gray) End program graytest