Convert byte array into any base

前端 未结 9 2490
梦如初夏
梦如初夏 2021-02-13 17:58

I have an array of bytes (any length), and I want to encode this array into string using my own base encoder. In .NET is standard Base64 encoder, but w

9条回答
  •  我寻月下人不归
    2021-02-13 18:10

    Here is a copy from my blog which I hope helps how (and why) I convert to Base62

    I am currently working on my own url shortener: konv.es. In order to create the shortest possible character hash of the url, I use the GetHashCode() method of the string, then convert the resulting number to base 62 ([0-9a-zA-Z]). The most elegant solution that I have found thus far to make the convertion (which is also a handy-dandy example of a yield return) is:

    public static IEnumerable ToBase62(int number)
        {
            do
            {
                yield return "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"[number % 62];
                number /= 62;
    
            } while (number > 0);
        }
    

    Extra credit: re-factor as an extension method

提交回复
热议问题