SoFunction
Updated on 2025-03-06

How to convert strings and byte arrays in C#

1. Encoding (converting to byte array) GetBytes

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

Only 7 bits are used per character, from 00h-7Fh. Only 128 characters can be expressed. Can't represent Chinese characters.

byte[] b = ("yourstring");
(("-", (p => ())));

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

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

byte[] b = ("Haaaa1");

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

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

byte[] b = ("gb2312").GetBytes("Haaaa1");//Traditional Chinese "big5"(("-", (p => ())));

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

In UTF-8, a Chinese character corresponds to three bytes, and a Chinese character in GB2312 takes up two bytes.
Regardless of the encoding, the alphanumeric numbers are not encoded, and a special symbol takes up one byte after encoding.

2. Decoding (converting into string): GetString, GetChars

(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 as Base64 numbers) to an equivalent 8-bit unsigned array of integers.

byte[] bt=Convert.FromBase64String("String");

2. Convert the value of an 8-bit unsigned integer array to its equivalent string representation encoded by Base64 numerically.

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

4. Conversion of byte array and character array

1. Character array to byte array

().GetBytes(char[],,byte[],0,true)

2. Byte array to character array

().GetChars(byte[],,char[],0)

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.