0

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)?

xofz
  • 5,600
  • 6
  • 45
  • 63
  • 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 Answers4

2

System.Text.Encoding.ASCIIEncoding.GetBytes(x.ToString());

Steve Danner
  • 21,818
  • 7
  • 41
  • 51
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
  • 13
1

You can use the division and modulo operators:

byte[] data = new byte[] { (byte)(48 + x / 10), (byte)(48 + x % 10) };
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
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
  • 17,802
  • 19
  • 72
  • 101