How to convert a number to an arbitrary radix?
What开发者_Go百科 I really want to do is convert DateTime.Now.Ticks to the shortest possible string without losing any precision. How is this possible? Let's assume we're using 7bit ASCII character set.
If only printable characters should be used, then you are limited to 32..127, so that is really base 96. Otherwise, base 128.
To convert to base 96, keep dividing by 96. The remainder+32 will be the character that you prepend to the string that you are building. Something like this:
static string ConvertBase96 (long value) {
string str = "";
while (value > 0) {
char rem = (char)((value % 96) + 32);
str = rem.ToString () + str;
value /= 96;
}
return str;
}
I would use System.BitConverter
to convert the long to a byte array, then System.Convert.ToBase64String
. You can reverse it with corresponding methods on both classes.
精彩评论