Rice coding: Difference between revisions
m
→{{header|Phix}}: use
imported>Tybalt89 |
m (→{{header|Phix}}: use) |
||
Line 171:
=={{header|Phix}}==
{{trans|Julia}}
function rice_encode(integer n, k=2, bool extended=false)
if extended then n = iff(n<0 ? -2*n-1 : 2*n) end if
assert(n>=0)
integer m = power(2,k), q = floor(n/m), r = rmdr(n,m)
return repeat('1',q)&sprintf(sprintf("%%0%db",k+1),r)
end function
function rice_decode(string a, integer k=2, bool extended=false)
integer m = power(2,k),
q = find('0',a),
r = to_integer(a[q+1..$],0,2),
i = (q-1) * m + r
if extended then i := iff(odd(i) ? -(i+1)/2 : i/2) end if
return i
end function
printf(1,"Base Rice Coding:\n")
for n=0 to 10 do
string s = rice_encode(n)
printf(1,"%d -> %s -> %d\n",{n,s,rice_decode(s)})
end for
printf(1,"Extended Rice Coding:\n")
for n=-10 to 10 do
string s = rice_encode(n,2,true)
printf(1,"%d -> %s -> %d\n",{n,s,rice_decode(s,2,true)})
end for
{{out}}
Same as Julia. Note that rice_decode on an input stream should probably get r from a[q+1..q+k] and strip q+k bits off the head of the stream.<br>
|