Rice coding: Difference between revisions

Content added Content deleted
(Added Algol 68)
Line 239: Line 239:
{{Trans|Julia|Using strings to represent the bit vector}}
{{Trans|Julia|Using strings to represent the bit vector}}
<syntaxhighlight lang="lua">
<syntaxhighlight lang="lua">
do -- Rice encoding - translated from the Julia sample
do -- Rice encoding - translation of the Julia sample


-- Golomb-Rice encoding helper function
local function do_rice_encode( q, r, k )
local result = {}
for i = 1, q do result[ #result + 1 ] = "1" end
result[ #result + 1 ] = "0"
local dPos, digits, v = #result + 1, 0, r
while v > 0 do
digits = digits + 1
local d = v % 2
v = math.floor( v / 2 )
table.insert( result, dPos, d ~= 0 and "1" or "0" )
end
for pad = digits + 1, k do table.insert( result, dPos, "0" ) end
return table.concat( result, "" )
end
-- Golomb-Rice encoding of a positive number to a bit vector (string of 0s and 1s) using M of 2^k
-- Golomb-Rice encoding of a positive number to a bit vector (string of 0s and 1s) using M of 2^k
local function rice_encode( n, k )
local function rice_encode( n, k )
Line 261: Line 246:
k = k or 2
k = k or 2
local m = math.floor( 2^k )
local m = math.floor( 2^k )
local q, r = math.floor( n / m ), n % m
local result, q, r = {}, math.floor( n / m ), n % m
return do_rice_encode( q, r, k )
while r > 0 do
result[ #result + 1 ] = r % 2 == 0 and "0" or "1"
r = math.floor( r / 2 )
end
while #result < k do result[ #result + 1 ] = "0" end
result[ #result + 1 ] = "0"
for i = 1, q do result[ #result + 1 ] = "1" end
return string.reverse( table.concat( result, "" ) )
end
end
-- see wikipedia.org/wiki/Golomb_coding#Use_with_signed_integers
-- see wikipedia.org/wiki/Golomb_coding#Use_with_signed_integers
Line 286: Line 278:


local function extended_rice_decode( a, k )
local function extended_rice_decode( a, k )
k =k or 2
k = k or 2
local i = rice_decode( a, k )
local i = rice_decode( a, k )
return math.floor( i % 2 == 1 and - ( ( i + 1 ) / 2 ) or i / 2 )
return math.floor( i % 2 == 1 and - ( ( i + 1 ) / 2 ) or i / 2 )