Reputation: 111
I am working on security related project,in that project currently i converted data to base64 format.But size of converted base64 data is more,for this purpose i want to convert a data to base128 format.How to Encode and Decode data in base128 string format in c#?
Upvotes: 1
Views: 7936
Reputation: 1933
I would strongly recommend against Base128 encoding if you can avoid it. A 7 bit alphabet would have to contain unprintable ASCII control characters (there are only 94 printable characters aka below codepoint 0x20). Many systems will fall over if you attempt to give them this type of data. It really does not seem to be worth the small amount of space savings you would get for the extra bit. Something like ASCII85 or Base91 may satisfy your needs without the headaches. See this SO post on a similar question.
However if you are persistent then you should be able to modify the mapping string in the following to get what you need. (NOTE: you will have to use the correct unprintable code for the characters you want to add to mapping like this "\x09"):
public static string GetStringFromByteArray(byte[] data)
{
string mapping = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvqwxyz!#$%&()*+-;<=>?@^_`{|}~',./:[]\\\"";
BigInteger base10 = new BigInteger(data);
string baseX;
int base=mapping.Length;
var result = new Stack<char>();
do
{
result.Push(mapping[(int)(base10 % base)]);
base10 /= base;
} while (base10 != 0);
baseX = new string(result.ToArray());
return baseX;
}
Upvotes: 7