Strange characters returned from byte stream?
-
21-08-2019 - |
Question
When trying to display a byte stream from HLDS (Half-Life Dedicated Server) in a textbox, it displays strange blocky question mark characters that look something like this:
[?]
Here's a sample line from the byte stream (with [?] in place of the strange character):
CPU In Out Uptime Users FPS Players[?] 0.00 0.97 0.91 2806 182 297.25 1[?]
Here is how I display the byte stream as a string:
byte[] bytes = listener.Receive(ref sender); // get bytes from stream
TextBox1.Text = Encoding.ASCII.GetString(bytes, 0, bytes.Length); // write to textbox
The characters are appearing where [CR][LF]
should normally appear. Why is it showing strange characters, and what can I do to remove the weird characters or correct the encoding?
***** UPDATE *****
Jon Skeet provided the right answer. The logs are returning \n for newline (not \r\n) and \0 at the end of each log line streamed. Replaced \n with Environment.NewLine and \0 with string.Empty and the strange characters are gone. Thank you Jon.
Solution
Firstly, I believe that if textboxes ever receive a character 0, they will assume that's the end of data - you may want to guard against that specifically.
Where does your byte stream come from? What encoding is it meant to be? What are the bytes at that point in the data?
OTHER TIPS
- Are you sure that the data is in pure ASCII? Is it perhaps in one of the many, many code-pages?
- Is it perhaps because of [CR] vs [LF] vs [CR][LF]?
- Can you tell use the bytes that are around "Players..."? And what you expect to see? We might be able to recognize the code-page
Presumably the byte is either in the codepage zone (128-255), or control characters (0-31).
You might have to replace them manually with linebreak characters that textbox will understand, or you may have to make your textbox multi-line if it isn't already.
Geekpedia says to just make sure you set:
TextBox1.MultiLine = true
After response:
If some of the characters aren'r CRLF, then you need to examine how you're getting them.
Look at the actual output from Encoding.ASCII.GetString()
and see what's in there.
The ones in you example are clearly line-end characters since they separate the header from the data line. CRLF should work in multiline textboxes so I'm not sure what's going on there (until you verify the byte contents) - the other characters may be replaced with spaces (that's one option).
And, I'm assuming the font of this text box will be fixed, not proportional since otherwise it won't line up very well.