Jump to content

Rice coding: Difference between revisions

julia example
mNo edit summary
(julia example)
Line 4:
 
Rice coding is initially meant to encode [[w:natural numbers|natural numbers]], but since [[w:relative numbers|relative numbers]] are [[w:countable|countable]], it is fairly easy to modify Rice coding to encode them too. You can do that for extra credit.
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">""" Golomb-Rice encoding of a positive number to bit vector using M of 2^k"""
function rice_encode(n::Integer, k = 2)
@assert n >= 0
m = 2^k
q, r = divrem(n, m)
return [fill(true, q); false; Bool.(reverse(digits(r, base=2, pad=k+1)))]
end
""" see wikipedia.org/wiki/Golomb_coding#Use_with_signed_integers """
extended_rice_encode(n, k = 2) = rice_encode(n < 0 ? -2n - 1 : 2n, k)
 
""" Golomb-Rice decoding of a vector of bits with M of 2^k """
function rice_decode(a::Vector{Bool}, k = 2)
m = 2^k
zpos = something(findfirst(==(0), a), 1)
r = evalpoly(2, reverse(a[zpos:end]))
q = zpos - 1
return q * m + r
end
extended_rice_decode(a, k = 2) = (i = rice_decode(a, k); isodd(i) ? -((i + 1) ÷ 2) : i ÷ 2)
 
println("Base Rice Coding:")
for n in 0:10
println(n, " -> ", join(map(d -> d ? "1" : "0", rice_encode(n))),
" -> ", rice_decode(rice_encode(n)))
end
println("Extended Rice Coding:")
for n in -10:10
println(n, " -> ", join(map(d -> d ? "1" : "0", extended_rice_encode(n))),
" -> ", extended_rice_decode(extended_rice_encode(n)))
end
</syntaxhighlight>{{out}}
<pre>
Base Rice Coding:
0 -> 0000 -> 0
1 -> 0001 -> 1
2 -> 0010 -> 2
3 -> 0011 -> 3
4 -> 10000 -> 4
5 -> 10001 -> 5
6 -> 10010 -> 6
7 -> 10011 -> 7
8 -> 110000 -> 8
9 -> 110001 -> 9
10 -> 110010 -> 10
Extended Rice Coding:
-10 -> 11110011 -> -10
-9 -> 11110001 -> -9
-8 -> 1110011 -> -8
-7 -> 1110001 -> -7
-6 -> 110011 -> -6
-5 -> 110001 -> -5
-4 -> 10011 -> -4
-3 -> 10001 -> -3
-2 -> 0011 -> -2
-1 -> 0001 -> -1
0 -> 0000 -> 0
1 -> 0010 -> 1
2 -> 10000 -> 2
3 -> 10010 -> 3
4 -> 110000 -> 4
5 -> 110010 -> 5
6 -> 1110000 -> 6
7 -> 1110010 -> 7
8 -> 11110000 -> 8
9 -> 11110010 -> 9
10 -> 111110000 -> 10
</pre>
 
 
=={{header|raku}}==
4,105

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.