views:

3267

answers:

3
+4  Q: 

sprintf in C#?

Is there something similar to sprintf() in C#?

I would for instance like to convert an integer to a 2-byte byte-array.

Something like:

int number = 17;
byte[] s = sprintf("%2c", number);
+13  A: 
string s = string.Format("{0:00}", number)

The first 0 means "the first argument" (i.e. number); the 00 after the colon is the format specifier (2 numeric digits).

However, note that .NET strings are UTF-16, so a 2-character string is 4 bytes, not 2

(edit: question changed from string to byte[])

To get the bytes, use Encoding:

byte[] raw = Encoding.UTF8.GetBytes(s);

(obviously different encodings may give different results; UTF8 will give 2 bytes for this data)

Actually, a shorter version of the first bit is:

string s = number.ToString("00");

But the string.Format version is more flexible.

Marc Gravell
+3  A: 

EDIT: I'm assuming that you want to convert the value of an integer to a byte array and not the value converted to a string first and then to a byte array (check marc's answer for the latter.)

To convert an int to a byte array you can use:

byte[] array = BitConverter.GetBytes(17);

but that will give you an array of 4 bytes and not 2 (since an int is 32 bits.) To get an array of 2 bytes you should use:

byte[] array = BitConverter.GetBytes((short)17);

If you just want to convert the value 17 to two characters then use:

string result = string.Format("{0:00}", 17);

But as marc pointed out the result will consume 4 bytes since each character in .NET is 2 bytes (UTF-16) (including the two bytes that hold the string length it will be 6 bytes).

Y Low
+2  A: 

It turned out, that what I really wanted was this:

short number = 17;
System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream);
writer.Write(number);
writer.Flush();

The key here is the Write-function of the BinaryWriter class. It has 18 overloads, converting different formats to a byte array which it writes to the stream. In my case I have to make sure the number I want to write is kept in a short datatype, this will make the Write function write 2 bytes.

Markus Johansson
If you are using a stream then your solution works very well, but for simple conversion you can use the BitConverter class (check my answer.)
Y Low
Yes, I agree. I stumbled upon that aswell..
Markus Johansson