How do I get the STX character of hex 02 - c#

I have a device to which I'm trying to connect via a socket, and according to the manual, I need the "STX character of hex 02".
How can I do this using C#?

Just a comment to GeoffM's answer (I don't have enough points to comment the proper way).
You should never embed STX (or other characters) that way using only two digits.
If the next character (after "\x02") was a valid hex digit, that would also be parsed and it would be a mess.
string s1 = "\x02End";
string s2 = "\x02" + "End";
string s3 = "\x0002End";
Here, s1 equals ".nd", since 2E is the dot character, while s2 and s3 equal STX + "End".

You can use a Unicode character escape: \u0002

Cast the Integer value of 2 to a char:
char cChar = (char)2;

\x02 is STX Code you can check the ASCII Table
checkFinal = checkFinal.Replace("\x02", "End").ToString().Trim();

Within a string, clearly the Unicode format is best, but for use as a byte, this approach works:
byte chrSTX = 0x02; // Start of Text
byte chrETX = 0x03; // End of Text
// etc...

You can embed the STX within a string like so:
byte[] myBytes = System.Text.Encoding.ASCII.GetBytes("\x02Hello, world!");
socket.Send(myBytes);

Related

Convert special character in string into a char

I have this string:
string specialCharacterString = #"\n";
where "\n" is the new line special character.
Is it possible convert/assign that string (of two characters) into a (single) char. How do I do something like:
char specialCharacter = Parse(specialCharacterString);
Where specialCharacter value would be equal to \n
Is there anything in dotnet that would parse the string for me or must I use if or switch the string (the string can contain any special character) to accomplish what I want. Note that char.Parse(string) cannot handle special characters and thinks the string above is actually two characters.
Maybe I am oversimplifying but can't you just do the following:
txtString.Replace("\n", "$");
It is technically a string to string replacement but would be string to char...
You can always cast it to a char since you know what char you are replacing the string with.
Not sure, what business need it is, but if you need parsing C# in C# you can use some tools like Antlr, which supports C# grammar (https://github.com/antlr/grammars-v4/)
I don't think there is any ready tool designed just for strings
Try use Regex.Unescape(specialCharacterString);
It will return the new string with escape characters.
For example:
var literalStringWithEscapeCharacters = #"Hello\tWorld";
var stringWithEscapeCharacters = Regex.Unescape(literalStringWithEscapeCharacters);
Console.WriteLine(stringWithEscapeCharacters);
Will print: Hello World
Instead of: Hello\tWorld
Then you can find escape characters in stringWithEscapeCharacters like this:
var escapeChars= new [] { '\n' };
var characters = stringWithEscapeCharacters.Where(c => escapeChars.Contains(c)).ToList();
All escape characters described here:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/#string-escape-sequences

Convert UTF-8 literals to readable string, C#?

I have a string as follows
const string nameString = #"\xda\xa9\xd8\xa7\xd8\xb1\xd8\xa8\xd8\xb1";
I tried:
var name = Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(nameString));
Not work.
You can find real characters here:
https://utf8-chartable.de/unicode-utf8-table.pl?start=1536&number=128&names=-&utf8=string-literal
e.g:
U+0631 ر \xd8\xb1
How can we convert it to readable string in C#?
Well, we have to parse: each "\xa9" should be converted into byte 0xa9
const string nameString = #"\xda\xa9\xd8\xa7\xd8\xb1\xd8\xa8\xd8\xb1";
We can do it with a help of regular expressions:
byte[] data = Regex
.Matches(nameString, #"\\x(?<value>[0-9a-fA-F]{1,2})")
.Cast<Match>()
.Select(match => (Convert.ToByte(match.Groups["value"].Value, 16)))
.ToArray();
Let's have a look at the data:
// da a9 d8 a7 d8 b1 d8 a8 d8 b1
Console.WriteLine(string.Join(" ", data.Select(b => b.ToString("x2"))));
Finally, we want to encode data to string; assuming that we should use UTF8:
string name = Encoding.UTF8.GetString(data);
Console.WriteLine(name);
Outcome:
کاربر
Using # sign causes escape sequences to be interpreted literally. Remove # sign to achieve desired result.
For more information see # (C# Reference).
The # character in this instance defines a verbatim string literal. Simple escape sequences (such as "\" for a backslash), hexadecimal escape sequences (such as "\x0041" for an uppercase A), and Unicode escape sequences (such as "\u0041" for an uppercase A) are interpreted literally.

How can I get third and fourth letters from string?

I want to get third and fourth letters from PlayerPrefs.GetString("String")
and Parse to int.
for example;
string playerLevelstr = PlayerPrefs.GetString("Player")[2] + PlayerPrefs.GetString("Player")[3];
//My Player string is "0012000000" but when I plus third and fourth letter, playerLevelstr should be "12" but it is "96".
int playerLevelint = int.Parse(playerLevelstr);
The indexer on a string returns a char.
If you use the + operator on chars together, it essentially does integer math on the two chars.
See this question for more information on that.
Though that means you should get 99 ('1' is 49, '2' is 50') not 96. But maybe that was a typo on one end or the other?
Regardless, you should either convert the chars to strings (.ToString() on them) or use the Substring function on the string instead. And don't forget your length/null checks!
This code PlayerPrefs.GetString("Player")[2] returns a char, which is being being converted to int (being the ASCII value of the character) when you add it to another char.
Do this instead:
string playerLevelstr = PlayerPrefs.GetString("Player").Substring(2,2);

How to detect SUB character and remove it from a text file in C#?

I am writing a program to process special text files. Some of these text files end with a SUB character (a substitute character. It may be 0x1A.) How do I detect this character and remove it from the text file using C#?
If it's really 0x1A in the binary data, and if you're reading it as an ASCII or UTF-8 file, it should end up as U+001A when read in .NET. So you may be able to write something like:
string text = File.ReadAllText("file.txt");
text = text.Replace("\u001a", "");
File.WriteAllText("file.txt", text);
Note that the "\u001a" part is a string consisting of a single character: \uxxxx is an escape sequence for a single UTF-16 code point with the given Unicode value expressed in hex.
The easiest answer would probably be a Regex:
public static string RemoveAll(this string input, char toRemove)
{
//produces a pattern like "\x1a+" which will match any occurrence
//of one or more of the character with that hex value
var pattern = #"\x" + ((int)toRemove).ToString("x") + "+";
return Regex.Replace(input, pattern, String.Empty);
}
//usage
var cleanString = dirtyString.RemoveAll((char)0x1a);
Yes, you could just pass in the int, but that requires knowing the integer value of the character. using a char as a parameter allows you to specify a literal or char variable with less muck.
C# has a method to detect control characters (including SUB).
See msdn : https://msdn.microsoft.com/en-us/library/9s05w2k9(v=vs.110).aspx
You could also try something like this it should work
using (FileStream f = File.OpenRead("path\\file")) //Your filename + extension
{
using (StreamReader sr = new StreamReader(f))
{
string text = sr.ReadToEnd();
text = text.Replace("\u001a", string.Empty);
}
}

Convert Integer to Ascii string in C#

I want to convert an integer to 3 character ascii string. For example if integer is 123, the my ascii string will also be "123". If integer is 1, then my ascii will be "001". If integer is 45, then my ascii string will be "045". So far I've tried Convert.ToString but could not get the result. How?
int myInt = 52;
string myString = myInt.ToString("000");
myString is "052" now. Hope it will help
Answer for the new question:
You're looking for String.PadLeft. Use it like myInteger.ToString().PadLeft(3, '0'). Or, simply use the "0" custom format specifier. Like myInteger.ToString("000").
Answer for the original question, returning strings like "0x31 0x32 0x33":
String.Join(" ",myInteger.ToString().PadLeft(3,'0').Select(x=>String.Format("0x{0:X}",(int)x))
Explanation:
The first ToString() converts your integer 123 into its string representation "123".
PadLeft(3,'0') pads the returned string out to three characters using a 0 as the padding character
Strings are enumerable as an array of char, so .Select selects into this array
For each character in the array, format it as 0x then the value of the character
Casting the char to int will allow you to get the ASCII value (you may be able to skip this cast, I am not sure)
The "X" format string converts a numeric value to hexadecimal
String.Join(" ", ...) puts it all back together again with spaces in between
It depends on if you actually want ASCII characters or if you want text. The below code will do both.
int value = 123;
// Convert value to text, adding leading zeroes.
string text = value.ToString().PadLeft(3, '0');
// Convert text to ASCII.
byte[] ascii = Encoding.ASCII.GetBytes(text);
Realise that .Net doesn't use ASCII for text manipulation. You can save ASCII to a file, but if you're using string objects, they're encoded in UTF-16.

Categories