
Code: Select all
;Albert (Psychophanta) February 2008:
Procedure.l BinaryCodingToGrayCoding(n.l)
ProcedureReturn n!(n>>1)
EndProcedure
Procedure.l GrayCodingToBinaryCoding(n.l)
Protected t.l=Int(Log(n)/Log(2))
Repeat
n!(Int(Pow(2,t))&n>>1):t-1
Until t<0
ProcedureReturn n
EndProcedure
;Test it:
For t.l=1 To 1000
a.l=Random(3000000)
If a<>BinaryCodingToGrayCoding(GrayCodingToBinaryCoding(a))
Debug "wrong!"
EndIf
Next

EDIT 20070219:
In assembler only for longs, not quads supported:
Code: Select all
;Albert (Psychophanta) February 2008:
Procedure.l BinaryCodingToGrayCodingASM(n.l)
!mov eax,dword[p.v_n]
!mov ebx,eax
!shr ebx,1
!xor eax,ebx
ProcedureReturn
EndProcedure
Procedure.l GrayCodingToBinaryCodingASM(n.l)
!mov cl,1
!mov eax,dword[p.v_n]
!@@:mov ebx,eax
!shr ebx,cl
!xor eax,ebx
!shl cl,1
!cmp ebx,2
!jc @f
!cmp cl,32; <- 64 if quads (.q) instead of longs (.l)
!jnz @r
!@@:
ProcedureReturn
EndProcedure
;Test it:
For t.l=1 To 10000
a.l=Random(3000000)
b.l=BinaryCodingToGrayCodingASM(GrayCodingToBinaryCodingASM(a))
If a<>b
Debug "wrong!"
EndIf
Next
Ah! btw, if anyone (for any strange reason) wants a quad ASM standard i386 version (much faster & better than the one from Demivec because this one allows values from 0 to 2^64-1), ask for it
