开发者

C# byte array problem

开发者 https://www.devze.com 2023-03-05 15:45 出处:网络
I found this code snippet on a blog as a\"Convert Binary dat开发者_JAVA技巧a to text\" Byte[] arrByte = {0,0,0,1,0,1};

I found this code snippet on a blog as a "Convert Binary dat开发者_JAVA技巧a to text"

Byte[] arrByte = {0,0,0,1,0,1};

string x = Convert.ToBase64String(arrByte);
System: Console.WriteLine(x);

And this provides a output of AAAAAQAB ..

What is not clear is that how 000101 -> is mapped to AAAAAQAB, and will I able to use this to all a-z characters as a binary equivalent and how? or is there a any other method ?


Actually 00000000 00000000 00000000 00000001 00000000 00000001 is mapped to AAAAAQAB because base64 uses 6 bits per letter so:

000000 = A (0)
000000 = A
000000 = A
000000 = A
000000 = A
010000 = Q  (16)
000000 = A
000001 = B  (1)

See this Wikipedia article for more details.


The method you are using, ToBase64String is the following. (from wiki)

Base64 is a group of similar encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The Base64 term originates from a specific MIME content transfer encoding.

To use a string as a byte[] or the other way you can use Encoding

Encoding.UTF8.GetString(bytes);

So

72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100

is equals to

Hello World

To bytes and from bytes:

var bytes = Encoding.UTF8.GetBytes("Hello world");
var str   = Encoding.UTF8.GetString(bytes);
0

精彩评论

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