Compressing hex string into base64 string

compressLooseWeight

How would you convert / compress 64 character long hex string (0-9a-f) into shortest possible web-safe-char string? (base64 chars is fine) The reverse algorithm must be able to “uncompress” resulting string back into original hex.

I have created p16Top64() compress algorithm and p64Top16() uncompress (reversed) algorithm based on ByteArray class and writeUnsignedInt(), readUnsignedInt() methods. Both p16Top64() and p64Top16() methods are now part of sk.yoz.data.Serialization class. By using p16Top64() method I was able to compress original 64 chars into 44 chars. But, is it possible to compress it into less than 44 char long base64 (0-9a-Z/=) string?

To be more specific lets assume your original string is:

295eb2c90b37696bb9256d05e404ad037078092214ce73cbe838302a04818507

My compress and uncompress methods:

import com.dynamicflash.util.Base64; // !use this Base64 class!

public static function p16Top64(p16:String):String
{
    var b:ByteArray = new ByteArray();
    var s:String = p16;
    while(s.length)
    {
        b.writeUnsignedInt(parseInt("0x" + s.substr(0, 8), 16));
        s = s.substr(8);
    }
    b.position = 0;
    return Base64.encodeByteArray(b);
}

public static function p64Top16(p64:String):String
{
    var r:String = "";
    var b:ByteArray = Base64.decodeToByteArray(p64);
    var x:String = "";
    b.position = 0;
    while(b.position < b.length)
    {
        x = b.readUnsignedInt().toString(16);
        r += String("00000000").substr(x.length) + x;
    }
    return r;
}

Lets test it:

Serialization.p16Top64("295eb2c90b37696bb9256d05e404ad037078092214ce73cbe838302a04818507")
// returns 64 chars.: KV6yyQs3aWu5JW0F5AStA3B4CSIUznPL6DgwKgSBhQc=

This is more less first time I have used ByteArray this way, so maybe there is even a better usage. If you can think of one, just let me know.

2 comments so far

  1. Richardus RiZki Karuniawan February 8, 2014 13:51

    whether it be for compres sms messages.,.,..,

    and please your example implementation in android eclipse,,.,.,.Thank you

  2. tensor June 18, 2014 21:36

    You can get an even better compression if you use base91.
    With the same hex string from your examle I got
    k_QmaI=z[#F1F9Q@4kdAgq&F,uo[rxAKf7nL{uHA

    Not too bad, ain’t it?

    Anyway thanks for the code you gave me a good idea.

Leave a comment

Please be polite and on topic. Your e-mail will never be published.