What 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.
+4
A:
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;
}
Tarydon
2010-01-08 08:50:24
tarydon: Good answer. But I think a code fragment might help him though
Toad
2010-01-08 08:55:25
@reinier: Fixed that.
Tarydon
2010-01-08 08:56:51
There needs to be a lot more iteration than that. Your explanation would only ever return the last base-96 digit, i.e. the units. I think you mean modulo 96 of the value, prepend (remainder + 32) to the digit string you have, subtract it from the source value, divide that by 96 and start again. Keep going until your value is zero.
Lazarus
2010-01-08 09:12:09
@Lazarus: That's what the code fragment is doing. And I *did* write *keep dividing by 96*. Plus, you don't have to subtract it from the source value, as you're going to divide the source value by 96 anyway.
Tarydon
2010-01-08 09:14:16
+3
A:
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.
Matt Greer
2010-01-08 08:53:26