How to write ASCII special characters in a .Net string
Suppose I want to use the ASCII special character FS(0x1C) in a .Net string, and then be able to format a byte array from that same string with the special character properly represented as a single byte, how would I do t开发者_如何学编程hat? I can't seem to get my head around it.
Thanks for any help you can give.
It rather depends on the nature of the serial port data format. If the data consists of mostly ASCII text characters interspersed with the occasional control character, then you can embed them in the string, e.g.
var data1 = Encoding.ASCII.GetBytes("Foo\x1CBar\x1CBaz");
However, if the data consists of several fields of various data types, then the BitConverter
class may be more useful, e.g.
var data2 = new List<byte>();
// Add an int value
data2.AddRange(BitConverter.GetBytes(6));
// Add a control character
data2.Add(0x1C);
// Add an ASCII-encoded string value
data2.AddRange(Encoding.ASCII.GetBytes("Hello"));
As others have pointed out, ASCII is not the only string encoding you could use, but from a serial port it is the most likely.
Here is how to embed it in a string:
"\x1C"
Is the string representation of that single character. Suppose you wanted to get it out as an array of bytes:
byte[] bytes = Encoding.ASCII.GetBytes("\x1C");
And if you wanted to get a string from an array of bytes:
string s = Encoding.ASCII.GetString(bytes);
Be aware that there are also more encodings, like UTF8, in the Encoding namespace that might work better depending on your neeed - though reading from a serial line you probably want plain ASCII.
You should look at the ASCIIEncoding class http://msdn.microsoft.com/en-us/library/system.text.asciiencoding.aspx If you want to deal with ASCII. .Net strings are unicode (UCS2). If you want a specific encoding you need to use one of the encoding classes.
You can embed a non printable character by escaping it "My string \x1c"
精彩评论