If I have int x = 24, how can I convert that into a 2-byte array where the first byte stores the value for 2 (50) and the second byte stores the value for 4 (52)?
Asked
Active
Viewed 800 times
0
xofz
- 5,500
- 6
- 43
- 61
-
Possible duplicate of http://stackoverflow.com/questions/400733/how-to-get-ascii-value-of-string-in-c-sharp with the variation of adding a ToString() to the front. – Ani May 07 '12 at 19:57
4 Answers
1
Easiest way is to convert to a String first, then convert that to bytes.
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(x.ToString());
Keith Robertson
- 791
- 7
- 12
1
You can use the division and modulo operators:
byte[] data = new byte[] { (byte)(48 + x / 10), (byte)(48 + x % 10) };
Guffa
- 666,277
- 106
- 705
- 986
0
int x_int = 24;
string x_string = x_int.ToString();
var x_bytes = (from x in x_string select Convert.ToByte(x)).ToArray();
galets
- 16,973
- 19
- 70
- 100