Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Compress positive integers

by ikegami (Patriarch)
on Apr 07, 2008 at 23:08 UTC ( [id://678854]=note: print w/replies, xml ) Need Help??


in reply to Compress positive integers

For starters, you'd get better compressing using one of the numerous compression modules on CPAN. (Some sample queries: Compress, gzip, zip)

The technique used by the code you posted is useful to save space on disk when dealing with lots of small numbers. It takes fewer bytes to save small numbers, and an extra byte to save very large numbers. It's advantage over general purpose compression algorithms is that you can seek to known and unknown positions into the file.

1 byte: 0..127 2 bytes: 128..etc 3 bytes: 16_384 4 bytes: 2_097_152 5 bytes: 268_435_456 6 bytes: 34_359_738_368 7 bytes: 4_398_046_511_104 8 bytes: 562_949_953_421_312 9 bytes: 72_057_594_037_927_936

Depending on the size of the ints on your system and the precision of floats on your system, some of the above aren't available or more than the above is available.

Untested:

sub compress_uint { my ($uint) = @_; my $compressed = ''; while ($uint >= 128) { $compressed .= chr(($uint & 127) | 128); $uint >>= 7; } $compressed .= chr($uint); } for (100, 1000, 100000) { print $fh compress_uint($_); }
sub decompress_uint { our $compressed; local *compressed = \($_[0]); my $bytes_read = 0; my $uint = 0; for (;;) { die if length($compressed) == $bytes_read; my $byte = ord(substr($compressed, $bytes_read++, 1)); $uint = ($uint << 7) | ($byte & 127); last if $byte & 128; } $compressed = substr($compressed, $bytes_read); } my $raw = do { local $/; <$fh> }; my @nums; while (length($raw)) { push @nums, decompress_uint($raw); }

Update: Fixed some typos in text and code.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://678854]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (2)
As of 2024-04-25 07:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found