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.
Related
For example,
string a = "4,3,2";
a.Split(',');
int one = Convert.ToInt32(a[0]);
int two = Convert.ToInt32(a[2]);
If I were to Console.WriteLine(a[0]); it will give me 4, and Console.WriteLine(a[2]) will give me 2. However, Console.WriteLine(one) and Console.WriteLine(two) gives me 52 and 50 respectively. Why is this so?
Character '4' is unicode codepoint 52 and character '3' unicode codepoint 51. You're converting characters instead of strings. The problem is that you're ignoring the result of a.Split(','); and then dereference the individual characters from a, and Convert.ToInt32(char) does:
Converts the value of the specified Unicode character to the
equivalent 32-bit signed integer.
and
The ToInt32(Char) method returns a 32-bit signed integer that
represents the UTF-16 encoded code unit of the value argument.
Instead use the strings after splitting:
string[] split = a.Split(',');
int one = Convert.ToInt32(split[0]);
int two = Convert.ToInt32(split[1]);
This is a very simple example:
class Program
{
static void Main(string[] args)
{
int val = 0;
Console.WriteLine(val.ToString()); // outputs: "0"
Console.WriteLine(val.ToString("#,#")); // outputs: "" <-- what if I want "0"!?!?
val = 1;
Console.WriteLine(val.ToString()); // outputs: "1"
Console.WriteLine(val.ToString("#,#")); // outputs: "1"
Console.Read();
}
}
There is a case where I have an int that contains a 0 value. I want this to appear as "0" but it's appearing as an empty string. Is it because 0 is the int's default value? Does the formatter assume that because it's default the output should be ""?
If you want 0, use #,0
# means optional
0 means mandatory
You can read more here: Custom Numeric Format Strings
The digit placeholder (#) is similar to the zero placeholder. It
defines the position of a digit within the resultant formatted string
and causes rounding after the decimal point. However, the digit
placeholder does not cause leading or trailing zeroes to be added to a
number where the original numeric value has no digit in the
appropriate position.
The digit placeholder has a side effect when converted a zero value to
a string. As the placeholder will not cause the creation of either
leading or trailing zeroes, when converting a zero value the resultant
string is empty.
C# Number to String Conversion
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);
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);
I want to generate a 4 character hex number.
To generate a hex number you can use
string.format("{0:X}", number)
and to generate a 4 char string you can use
string.format("{0:0000}", number)
Is there any way to combine them?
I'm assuming you mean: 4-digit hexadecimal number.
If so, then yes:
string.Format("{0:X4}", number)
should do the trick.
Have you tried:
string hex = string.Format("{0:X4}", number);
? Alternatively, if you don't need it to be part of a composite pattern, it's simpler to write:
string hex = number.ToString("X4");