For background see Re^9: Compress positive integers and the thread above which suggests an algorithm and the thread above which details the task.

Here is an implementation of the MSB serialisation strategy using fixed width 4 byte ints for simplicity.This task really asks to be implemented in C but can of course be done in Perl. << is a bitshift operator | is binary OR and & is binary AND.

use strict; use Data::Dumper; my $data = { 1 => [ 1..10 ], 2 => [ 11..20 ], 3 => [ 21..30 ], }; my $MSB = 1<<31; print "$MSB is MSB in decimal\n"; my $SET_MSB = pack "I",$MSB; printf "%s SET MASK in binary\n", (unpack "b32", $SET_MSB); my $UNSET_MSB = pack "I",$MSB-1; printf "%s UNSET MASK in binary\n", (unpack "b32", $UNSET_MSB); my $res = serialise($data); my $dat = unserialise($res); print Data::Dumper::Dumper($dat); sub serialise { my $data = shift; my $str = ''; for my $doc_id( keys %$data ) { $str .= (pack "I", $doc_id) | $SET_MSB; for my $pos ( @{$data->{$doc_id}} ) { $str .= (pack "I", $pos) & $UNSET_MSB; } } return $str; } sub unserialise { my $data = shift; my $dat = {}; my $doc_id = undef; for( my $i=0;$i<length $data; $i+=4) { my $int = unpack "I", (substr $data,$i); if ( $int > $MSB ) { $doc_id = unpack "I", ((pack "I", $int) & $UNSET_MSB); } else { push @{$dat->{$doc_id}}, $int; } } return $dat; }

In reply to Re: Byte allign compression in Perl.. by tachyon-II
in thread Byte allign compression in Perl.. by MimisIVI

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.