Recipe2.13.Converting a String Returned as a Byte Back into a String


Recipe 2.13. Converting a String Returned as a Byte[ ] Back into a String

Problem

Many methods in the FCL return a byte[] because they are providing a byte stream service, but some applications need to pass strings over these byte stream services. Some of these methods include:

 System.Diagnostics.EventLogEntry.Data System.IO.BinaryReader.Read System.IO.BinaryReader.ReadBytes System.IO.FileStream.Read System.IO.FileStream.BeginRead System.IO.MemoryStream // Constructor System.IO.MemoryStream.Read System.IO.MemoryStream.BeginRead System.Net.Sockets.Socket.Receive System.Net.Sockets.Socket.ReceiveFrom System.Net.Sockets.Socket.BeginReceive System.Net.Sockets.Socket.BeginReceiveFrom System.Net.Sockets.NetworkStream.Read System.Net.Sockets.NetworkStream.BeginRead System.Security.Cryptography.CryptoStream.Read System.Security.Cryptography.CryptoStream.BeginRead 

In many cases, this byte[] might contain ASCII-or Unicode-encoded characters. You need a way to recombine this byte[] to obtain the original string.

Solution

To convert a byte array of ASCII values to a complete string, use the following method:

 string constructedString = Encoding.ASCII.GetString(characters); 

To convert a byte array of Unicode values to a complete string, use the following method:

 string constructedString = Encoding.Unicode.GetString(characters); 

Discussion

The GetString method of the Encoding class (returned by the ASCII property) converts 7-bit ASCII characters contained in a byte array to a string. Any value larger than 127 (0x7F) will be ANDed with the value 127 (0x7F) and the resulting character value will be displayed in the string. For example, if the byte[] contains the value 200 (0xC8), this value will be converted to 72 (0x48), and the character equivalent of 72 (0x48) ('H') will be displayed. The Encoding class can be found in the System.Text namespace. The GetString method is overloaded to accept additional arguments as well. The overloaded versions of the method convert all or part of a string to ASCII and then store the result in a specified range inside a byte[].

The GetString method returns a string containing the converted byte[] of ASCII characters.

The GetString method of the Encoding class (returned by the Unicode property) converts Unicode characters into 16-bit Unicode values. The Encoding class can be found in the System.Text namespace. The GetString method returns a string containing the converted byte[] of Unicode characters.

See Also

See the "ASCIIEncoding Class" and "UnicodeEncoding Class" topics in the MSDN documentation.



C# Cookbook
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2004
Pages: 424

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net