
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
58
|
Chapter 2: Strings and Characters
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) con-
verts 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 charac-
ter 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 ...