How to convert string to byte array in C#

This article introduces the conversion method between strings and byte arrays in C#. It is introduced in great detail through sample code. It has certain reference value for everyone’s study or work. Friends in need can refer to it.

1. Encoding (converting into byte array) GetBytes

  1. ASII code: Each character in the string is represented by one byte.

Each character actually uses only 7 bits, from 00h-7Fh. Only 128 characters can be expressed. cannot represent Chinese characters,

1

2

byte[] b = Encoding.ASCII.GetBytes("yourstring");

Console.Write(string.Join("-", b.Select(p => p.ToString())));

   // Get: 121-111-117-114-115-116-114-105-110-103   

2. Unicode code: Each character in the string is represented by two bytes.

1

byte[] b = Encoding.Unicode.GetBytes("哈啊a1");

  // Get: 200-84-74-85-97-0-49-0

3. Simplified Chinese: Each Chinese character in the string is represented by two bytes, and other characters are represented by one byte.

1

2

byte[] b = Encoding.GetEncoding("gb2312").GetBytes("哈啊a1");//繁体中文”big5”

Console.Write(string.Join("-", b.Select(p => p.ToString())));

   // Get: 185-254-176-161-97-49

In UTF-8, one Chinese character corresponds to three bytes, and in GB2312, one Chinese character occupies two bytes. 
Regardless of the encoding, alphanumeric characters are not encoded, and special symbols occupy one byte after encoding.

2. Decoding (convert to string): GetString, GetChars

1

Encoding.XXX.GetString(byte[] data,[,index,count]);

3. Conversion of strings and byte arrays based on Base64 (ASCII) encoding

1. Convert the specified string (which encodes binary data into Base64 numbers) into an equivalent 8-bit unsigned integer array.

1

byte[] bt=Convert.FromBase64String("字符串");

2. Convert the value of the 8-bit unsigned integer array to its equivalent string representation encoded with Base64 numbers.

1

Convert.ToBase64String(byte[] data,[,index,count]);

Four, byte array and character array conversion

1. Character array to byte array

1

Encoding.XXX.GetEncoder().GetBytes(char[],0.length,byte[],0,true)

2. Byte array to character array

1

Encoding.XXX.GetDecoder().GetChars(byte[],0.length,char[],0)

The above is the entire content of this article. I hope it will be helpful to everyone’s study.

Reprinted from: Weidian Reading    https://www.weidianyuedu.com

Guess you like

Origin blog.csdn.net/weixin_45707610/article/details/131625785