C # byte array converted to string
If you want to find a way to convert between strings and byte arrays from the System.String class, I'm afraid you'll be disappointed. To make such a transition, we had to use another class: System.Text.Encoding. The class provides the bye[] GetBytes (String) method to convert a string to a byte array, and a string GetString (byte[]) method to convert a C # byte array to a string.
The System.Text.Encoding class does not seem to have a usable constructor, but we can find several default Encoding, Encoding.default (Gets the encoding of the system's current ANSI code page), Encoding.ascii (gets 7-bit ASCII Character set encoding), Encoding.unicode (Get encoding in Unicode format in Little-endian byte order), ENCODING.UTF7 (Get encoding in UTF-7 format), Encoding.UTF8 (get Encoding of UTF-8 format). Here the main talk about the difference between Encoding.default and encoding.unicode for conversion.
In the process of converting a string into a byte array, Encoding.default will each single-byte character, such as half-width in English, instead of each double-byte character, such as Kanji. Encoding.unicode will convert them to two bytes. We can get a simple look at the conversion method, and the difference between using Encoding.default and Encodeing.unicode:
- private void Teststringbytes () {
- String s = "C # language";
- Byte[] B1 = System.Text.Encoding.Default.GetBytes (s);
- byte[] b2 = System.Text.Encoding.Unicode.GetBytes (s);
- String t1 = " ", t2 = "";
- foreach (Byte B in B1) {
- T1 + = b.tostring ("") + "";
- }
- foreach (Byte b in B2) {
- T2 + = b.tostring ("") + "";
- }
- This.textBox1.Text = "";
- This.textBox1.AppendText ("B1. Length = "+ b1. Length + "\ n");
- This.textBox1.AppendText (t1 + "\ n");
- This.textBox1.AppendText ("B2. Length = "+ b2. Length + "\ n");
- This.textBox1.AppendText (t2 + "\ n");
- }
The operation result is as follows, do not say detailed, I believe everybody already understood.
- B1. Length = 6
- 67 35 211 239 209 212
- B2. Length = 8
- 67 0 35 0 237 139 0 138
Converts a C # byte array into a string, using the Encoding class's String GetString (byte[]) or a string GetString (byte[], int, int) method, which Encoding or is determined by the encoding. Add the following statement as an instance in the Teststringbytes () function:
- byte[] bs = {97, 98, 99, 100, 101, 102};
- String ss = System.Text.Encoding.ASCII.GetString (BS);
- This.textBox1.AppendText ("The string is:" + SS + "\ n");
The result of the operation is: the string is:abcdef
C # byte array converted to string