SoFunction
Updated on 2025-03-06

Method of converting between Byte[] and String in C#

This article will introduce to you how to convert between Byte[] and String?

Bit (b): The bit is only 0 1, 1 represents pulses, and 0 represents no pulses. It is the most basic unit of computer physical memory storage.

Byte (B): 8 bits, integer representation of 0-255

Encoding: Characters must be encoded before they can be processed by computers. Early computers used 7 as coding for AscII, and designed Chinese simplified Chinese GB2312 and big5 in order to process Chinese characters.

The conversion between a string and a byte array is actually a conversion between real-world information and digital world information, which inevitably involves a certain encoding method. Different encoding methods will lead to different conversion results. Commonly used in C# to manage commonly used encodings. The following code is directly listed:

using System;
using ;
using ;
using ;
using ;
namespace ByteToString
{
class Program
{
static void Main(string[] args)
{
string str = "Brother Ju is so handsome!";
//Use UTF encoding.  .  .Byte[] utf8 = StrToByte(str, Encoding.UTF8);
//Estimate C# There was no Chinese simplified Chinese when designing at that time. Is this what China did later?Byte[] gb2312 = StrToByte(str,("GB2312"));("This isUTF8(Brother Ju is so handsome),The length is:{0}",);
foreach (var item in utf8)
{
(item);
}
("\n\nThis isgb2312(Brother Ju is so handsome),The length is:{0}",);
foreach (var item in gb2312)
{
(item);
}
//Convert byte array encoded with utf8 to strstring utf8Str = ByteToStr(utf8,Encoding.UTF8);
string gb2312Str = ByteToStr(gb2312,("GB2312"));
("\n\nutf8: {0}",utf8Str);
("gb2312: {0}",gb2312Str);
();
}
//C#Usually encoding is used//To string to arraystatic Byte[] StrToByte(string str, Encoding encoding)
{
return (str);
}
//Array conversion stringstatic String ByteToStr(Byte[] bt,Encoding encoding)
{
return (bt);
}
}
}

The above is the method of converting Byte[] and String in C# introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!