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

Numbers as a stream of letters

by bl0rf (Pilgrim)
on Dec 28, 2003 at 03:13 UTC ( #317267=snippet: print w/replies, xml ) Need Help??
Description: Store a number as a string, while using up less space than if you were to write out the whole number. Example: The number 1819436368 (10 chars) can be stored as the string "Perl" (4 chars). Useful when you need to save on space. See node 317125.
#!/usr/bin/perl -W

  # Takes a number between 0 and 2^32,
  # returns 4 characters (ASCII).
sub num_to_chars  
my $packed = pack( "l", $_[0] );
return unpack( "A*", $packed );

  # Takes 4 ASCII chars, returns a "long"
sub chars_to_num
my $chars = pack( "A*", $_[0] );
return unpack( "l", $chars );

Replies are listed 'Best First'.
Re: Numbers as a stream of letters
by fx (Pilgrim) on Dec 28, 2003 at 19:25 UTC

    I have used methods such as this with CGI. I needed to pass values in URLs such as session IDs and user IDs. Using methods such as this, a long session ID becomes a short char string. It also, in my opinion, helps disuade people form putting "random" stuff into your URLs in the hope that something interesting is seen (I know that this won't stop someone with the relevant skills, but it might stop the wannabes).

    I agree with the previous comment that in native storage you gain nothing, but you can save space in other situations (such as URLs in e-mails where a long URL may wrap and become confusing).

    == fx, Infinity Is Colourless

Re: Numbers as a stream of letters
by exussum0 (Vicar) on Dec 28, 2003 at 04:02 UTC
    Ugh. Numbers are stored in their native formats. I.e. 2^32 is stored in 4 bytes (2^8 * 4). Turning 4mil and change into characters gets you no-where. If you want to argue efficiency of storage, which is cheap, at least compress ala gzip :)

    Play that funky music white boy..
Re: Numbers as a stream of letters
by bl0rf (Pilgrim) on Dec 29, 2003 at 01:46 UTC
    I was thinking of this as more of a storage benefit for homebrew ASCII databases, this will economize storage space on disk in applications where the database file is not compressed. After using the above code I noticed that CR and LF ASCII chars will appear in the files and thus mess up <FILE> operations...

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://317267]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (5)
As of 2017-01-22 06:53 GMT
Find Nodes?
    Voting Booth?
    Do you watch meteor showers?

    Results (186 votes). Check out past polls.