我有这行我需要用C#写
sprintf(
currentTAG,
"%2.2X%2.2X,%2.2X%2.2X",
hBuffer[ presentPtr+1 ],
hBuffer[ presentPtr ],
hBuffer[ presentPtr+3 ],
hBuffer[ presentPtr+2 ] );
hbuffer 是一个 uchar 数组。
在 C# 中,我在字节数组中有相同的数据,我需要实现这一行...
请帮忙...
请您参考如下方法:
检查这是否有效:
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]);
这是另一种选择,但效率较低:
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] 在 C/C++ %2.2X 中使用大写字母和至少两个字母输出十六进制值(左边用零)。
在 C++ 中,下一个示例在控制台中输出 01 61:
unsigned char test[] = { 0x01, 'a' };
printf("%2.2X %2.2X", test[0], test[1]);
使用以上信息,以下 C# 代码片段还在控制台中输出 01 61:
byte[] test = { 0x01, (byte) 'a' };
Console.WriteLine(String.Format("{0:X2} {1:X2}", test[0], test[1]));
