2

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?

1
  • 1
    Do you want ASCII or text? A string would be far easier to use but is not one byte per character. Commented Jul 30, 2012 at 5:41

3 Answers 3

10
int myInt = 52;
string myString = myInt.ToString("000");

myString is "052" now. Hope it will help

Sign up to request clarification or add additional context in comments.

Comments

5

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

7 Comments

Could you explain more on your answer?
Shoot, I missed you want it padded to a three-character string.
@FrédéricHamidi Yes I was just editing my answer to do that. It's done now.
Sorry guys. I think I ask the wrong question. I've edited my question again. Please review it again , thanks!
I need to transmit the integer out as ascii string from serial port.
|
5

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.