开发者

Understanding ToBase64String

开发者 https://www.devze.com 2023-04-05 06:22 出处:网络
string name = \"cem\" 开发者_StackOverflow社区byte[] barr = \"cem\".ToCharArray().Select(p=>Convert.ToByte(p)).ToArray();
string name = "cem"
开发者_StackOverflow社区byte[] barr = "cem".ToCharArray().Select(p=>Convert.ToByte(p)).ToArray();
string converted = Convert.ToBase64String(barr); // converted will be Y2Vt

  c    e    m
 99  101  109

  Y   2   V   t
 24  54  21  45

I couldn't get the math behind of this conversion.

base64 string encoding table: http://tipsforcdevelopers.blogspot.com/2009/05/difference-between-converttobase64strin.html


The table on Wikipedia's page explains it quite clear.

Each 3 bytes contains 3 x 8 = 24 bits.

These 24 bits are encoded into 4 ASCII characters in Base64 encoding. Which means each ASCII char carries 6 bits of data.

2^6 is 64 so it is possible to use the table to map each 6 bits to an ASCII char.

Understanding ToBase64String


It's a specific case of base conversion from base 256 to base 64.

To do the math on paper, first convert the numbers to decimal. Here I 've converted both:

              c               e              m
              99 * 256²       101 * 256¹     109 * 256°
              6488064         25856          109         => sum = 6514029

y             2               v              t
24 * 64³      54 * 64²        21 * 64¹       45 * 64°
6291456       221184          1344           45          => sum = 6514029

OK, so this also means that they are indeed the same number.

Then, to convert from decimal to another base (e.g. to base 64) find the largest power of 64 that is smaller than or equal to the decimal number (which is 6514029). That power is 64³ = 262144. Doing the integer division 6514029 / 262144 gives

6514029 / 262133 = 24, remainder = 6514029 - 262133 * 24 = 222573

This means that the first digit of the base64 number is going to be the 25th (we start counting from 0), which is indeed y.

Continuing the process with the remainder as the current decimal number will produce the rest of the digits. With this process you can convert a number in any base to any other base.

0

精彩评论

暂无评论...
验证码 换一张
取 消