g45rg34d
g45rg34d

Reputation: 9660

How to convert a number to an arbitrary radix?

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.

Upvotes: 0

Views: 821

Answers (2)

Matt Greer
Matt Greer

Reputation: 62027

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.

Upvotes: 4

Tarydon
Tarydon

Reputation: 5183

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;
  }

Upvotes: 5

Related Questions