3

So I'm trying to use a bluetooth module (HC-06) to read data sent to my Netduino board from my cell phone. However, I cant get the bytes converted into text so I can compare the characters I send and thus turn them into conditional statements. From what I've seen I need to use the following line of code in C# to change it from a byte array to a string, however I cannot find a definition for class in my scope!! Here is the line:

Encoding.ASCII.GetString();

And here is the error I'm getting:

'System.Text.Encoding' does not contain definition for 'ASCII'

I'm using the .Net Micro Framework version 4.1 with the Visual Studio Express 2012 IDE. I'm using the original Netduino, Netduino 1 with the 4.1 Framework.

Justin Gardner
  • 605
  • 2
  • 9
  • 17
  • Google is your friend. http://forums.netduino.com/index.php?/topic/3393-c-console-to-netduino-help/ – Haney Mar 21 '14 at 18:09
  • @DavidHaney Thanks for the link! Unfortunately that page doesn't resolve the issue, it provides an alternative route. – Justin Gardner Mar 21 '14 at 18:36

2 Answers2

3

ASCII encoding isn't included because it is not necessary. UTF-8 is the same as ASCII, the MSB is irrelevant in text streams. You should be able to get a correct textual representation using the UTF8 encoding, as long as the content was sent and received properly. For example, if buffer contains your received text...

Debug.Print(new String(Encoding.UTF8.GetChars(buffer, 0, buffer.Length)));

jinzai
  • 436
  • 3
  • 9
  • I disagree that this is not necessary. UTF8 is not the same as ASCII, it is a superset which includes all of ASCII, and 128 additional characters in the 1st byte, and up to 3 additional bytes. – Jessica Pennell Apr 05 '19 at 23:25
0

Encoding.ASCII exists in the .NET 4.7.2 standard, but not everywhere. See

https://learn.microsoft.com/en-us/dotnet/api/system.text.encoding.ascii?view=netframework-4.7.2

If, like me, you stumbled across this page because you are developing a portable library, you will notice toward the bottom of that page in the Applies To section that Encoding.ASCII is not available in all contexts.

Anywhere 7 bit encoding is not available, you will need to filter out any bytes that are 8 bit and above by hand and use Encoding.UTF8. An easy way to do this uses Regex replace. You can modify the below code if you are ok with allowing nulls inside your string, I exclude them.

String MyASCIIString = Encoding.UTF8.GetString(MyByteArray);
Regex NotASCII = new Regex("[^\u0001-\u007f]+");
MyASCIIString = NotASCII.Replace(MyASCIIString, "");
Jessica Pennell
  • 578
  • 4
  • 14