简体   繁体   English

sp #f在C#?

[英]sprintf in C#?

Is there something similar to sprintf() in C#? 在C#中有类似sprintf()东西吗?

I would for instance like to convert an integer to a 2-byte byte-array. 我想比如将整数转换为2字节的字节数组。

Something like: 就像是:

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

The first 0 means "the first argument" (ie number); 第一个0表示“第一个参数”(即数字); the 00 after the colon is the format specifier (2 numeric digits). 冒号后面的00是格式说明符(2位数字)。

However, note that .NET strings are UTF-16, so a 2-character string is 4 bytes, not 2 但请注意,.NET字符串是UTF-16,因此2个字符的字符串是4个字节,而不是2个字节

(edit: question changed from string to byte[] ) (编辑:问题从string更改为byte[]

To get the bytes, use Encoding : 要获取字节,请使用Encoding

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

(obviously different encodings may give different results; UTF8 will give 2 bytes for this data) (显然不同的编码可能会给出不同的结果; UTF8会为这些数据提供2个字节)

Actually, a shorter version of the first bit is: 实际上,第一位的较短版本是:

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

But the string.Format version is more flexible. 但是string.Format版本更灵活。

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.) 编辑:我假设您要将整数的值转换为字节数组,而不是先将值转换为字符串然后转换为字节数组(请检查marc对后者的答案。)

To convert an int to a byte array you can use: 要将int转换为字节数组,您可以使用:

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: 但是这将给你一个4字节而不是2的数组(因为int是32位。)要获得一个2字节的数组,你应该使用:

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

If you just want to convert the value 17 to two characters then use: 如果您只想将值17转换为两个字符,请使用:

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). 但正如marc所指出的那样,结果将占用4个字节,因为.NET中的每个字符都是2个字节(UTF-16)(包括保存字符串长度的两个字节,它将是6个字节)。

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. 这里的关键是BinaryWriter类的Write函数。 It has 18 overloads, converting different formats to a byte array which it writes to the stream. 它有18个重载,将不同的格式转换为写入流的字节数组。 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. 在我的情况下,我必须确保我想要写的数字保存在一个短数据类型中,这将使Write函数写入2个字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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