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?
3 Answers
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 integer123into its string representation"123". PadLeft(3,'0')pads the returned string out to three characters using a0as the padding character- Strings are enumerable as an array of
char, so.Selectselects into this array - For each character in the array, format it as
0xthen the value of the character - Casting the
chartointwill 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
7 Comments
maniac84
Could you explain more on your answer?
lc.
Shoot, I missed you want it padded to a three-character string.
lc.
@FrédéricHamidi Yes I was just editing my answer to do that. It's done now.
maniac84
Sorry guys. I think I ask the wrong question. I've edited my question again. Please review it again , thanks!
maniac84
I need to transmit the integer out as ascii string from serial port.
|
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.
stringwould be far easier to use but is not one byte per character.