简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM