开发者

Problem in converting sprintf to C#

i have this line I need to write in C#

开发者_高级运维
sprintf(
  currentTAG,
  "%2.2X%2.2X,%2.2X%2.2X",
  hBuffer[ presentPtr+1 ],
  hBuffer[ presentPtr ],
  hBuffer[ presentPtr+3 ],
  hBuffer[ presentPtr+2 ] );

hbuffer is a uchar array.

In C# I have the same data in a byte array and I need to implement this line...

Please help...


Check if this works:

byte[] hBuffer = { ... };
int presentPtr = 0;
string currentTAG = string.Format("{0:X2}{1:X2},{2:X2}{3:X2}",
                          hBuffer[p+1],
                          hBuffer[p],
                          hBuffer[p + 3],
                          hBuffer[p + 2]);

This is another option but less efficient:

byte[] hBuffer = { ... };
int presentPtr = 0;
string currentTAG = string.Format("{0}{1},{2}{3}",
                          hBuffer[p+1].ToString("X2"),
                          hBuffer[p].ToString("X2"),
                          hBuffer[p + 3].ToString("X2"),
                          hBuffer[p + 2].ToString("X2"));

Converting each byte of hBuffer to a string, as in the second example, is less efficient. The first example will give you better performance, especially if you do this many times, by virtue of not spamming the garbage collector.

[From the top of my head] In C/C++ %2.2X outputs the value in hexadecimal using upper case letters and at least two letters (left padded with zero).

In C++ the next example outputs 01 61 in the console:

unsigned char test[] = { 0x01, 'a' };
printf("%2.2X %2.2X", test[0], test[1]);

Using the information above, the following C# snippet outputs also 01 61 in the console:

byte[] test = { 0x01, (byte) 'a' };
Console.WriteLine(String.Format("{0:X2} {1:X2}", test[0], test[1]));


Composite Formatting: This page discusses how to use the string.Format() function.


You are looking for String.Format method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜