Convert a byte array to a string in C# | Techie Delight

文章推薦指數: 80 %
投票人數:10人

To decode all bytes in the byte array into a string, use the Encoding.GetString() method. Several decoding schemes are available in Encoding class – UTF8 ... Skiptocontent ThispostwilldiscusshowtoconvertabytearraytoastringinC#. 1.UsingEncoding.GetString()method Todecodeallbytesinthebytearrayintoastring,usetheEncoding.GetString()method.SeveraldecodingschemesareavailableinEncodingclass–UTF8,Unicode,UTF32,ASCII,etc. 123456789101112131415161718192021 usingSystem;usingSystem.Text; publicclassExample{    publicstaticvoidMain()    {        byte[]bytes=Encoding.Default.GetBytes("ABC123");        Console.WriteLine("ByteArrayis:"+String.Join("",bytes));         stringstr=Encoding.Default.GetString(bytes);        Console.WriteLine("TheStringis:"+str);    }} /*    Output:     ByteArrayis:656667495051    TheStringis:ABC123*/ Download  RunCode 2.UsingConvert.ToBase64String()method Todecodethebytesencodedwithbase-64digits,usetheConvert.ToBase64String()method.Thisisdemonstratedbelow: 1234567891011121314151617181920 usingSystem; publicclassExample{    publicstaticvoidMain()    {        byte[]bytes=Convert.FromBase64String("QUJDMTIz");        Console.WriteLine("ByteArrayis:"+String.Join("",bytes));         stringstr=Convert.ToBase64String(bytes);        Console.WriteLine("TheStringis:"+str);    }} /*    Output:     ByteArrayis:656667495051    TheStringis:QUJDMTIz*/ Download  RunCode 3.UsingMemoryStreamClass Here,theideaistocreatethebytestreamfromaspecifiedbytearray.Thenreadallcharactersfromthebytestreamandreturnthestreamasastring. Thefollowingcodeexampleshowshowtoimplementthis.Thesolutionautomaticallytriestodeterminetheencodingusedusingthebyteordermark(BOM)inthebytestream.Ifnotfound,UTF-8encodingisassumed. 1234567891011121314151617181920212223242526272829303132 usingSystem;usingSystem.Text;usingSystem.IO; publicclassExample{    staticstringBytesToString(byte[]bytes)    {        using(MemoryStreamstream=newMemoryStream(bytes))        {            using(StreamReaderstreamReader=newStreamReader(stream)){                returnstreamReader.ReadToEnd();            }        }    }     publicstaticvoidMain()    {        byte[]bytes=Encoding.ASCII.GetBytes("ABC123");        Console.WriteLine("ByteArrayis:"+String.Join("",bytes));         stringstr=BytesToString(bytes);        Console.WriteLine("TheStringis:"+str);    }} /*    Output:     ByteArrayis:656667495051    TheStringis:ABC123*/ Download  RunCode That’sallaboutconvertingabytearraytoastringinC#. RatethispostSubmitRatingAveragerating4.25/5.Votecount:24Novotessofar!Bethefirsttoratethispost.Wearesorrythatthispostwasnotusefulforyou!Tellushowwecanimprovethispost?SubmitFeedback Thanksforreading. PleaseuseouronlinecompilertopostcodeincommentsusingC,C++,Java,Python,JavaScript,C#,PHP,andmanymorepopularprogramminglanguages. Likeus?Referustoyourfriendsandhelpusgrow.Happycoding:) Subscribe Notifyof newfollow-upcomments newrepliestomycomments Name* Email* Name* Email* 3Comments MostVoted Newest Oldest InlineFeedbacks Viewallcomments ViewComments LoadMoreComments BrowseAlgorithm Beginner BinarySearch BitHacks Bottom-up Breadth-firstsearch Depth-firstsearch Easy FIFO Greedy Hard Hashing LIFO Medium MustKnow PriorityQueue Recursive SlidingWindow Top-down Trie Subscribetonewposts Enteryouremailaddresstosubscribetonewposts. EmailAddress Subscribe Thiswebsiteusescookies.Byusingthissite,youagreetotheuseofcookies,ourpolicies,copyrighttermsandotherconditions.ReadourPrivacyPolicy. Gotit DoNOTfollowthislinkoryouwillbebannedfromthesite! Insert



請為這篇文章評分?