需要帮助转换

需要帮助转换

问题描述:

嗨需要帮助该C转换++代码转换为C#需要帮助转换

sprintf((char *)(dataBuffer), "Failed statistics read, device %s", device); 

的DataBuffer为byte []

我写了这个,但错误将字符串转换为byte []

dataBuffer = string.Format("Failed statistics read, device {0}", device); 
+1

这是转换此语句的正确代码。那个'byte []'是什么意思? C++代码中没有字节数组。 – 2011-05-02 04:09:13

+0

@Jonathan Wood一个猜测(但只有猜测)是dataBuffer是byte []。部分由(char *)强制转换支持。 – 2011-05-02 04:11:14

+0

@icktoofay:如果是这样的话,那么原始代码就有缺陷,因为'%s'用于格式化数据,'%s'用于'char *'。这可能是一个字节数组被用来存储ASCII字符。但这仍然是有缺陷的。 – 2011-05-02 04:13:06

String str = string.Format("Failed statistics read, device {0}", device); 
byte[] dataBuffer = System.Text.Encoding.ASCII.GetBytes(str); 
// for 2-byte unicode 
byte[] dataBuffer = System.Text.Encoding.Unicode.GetBytes(str); 
// for UTF8 unicode 
byte[] dataBuffer = System.Text.Encoding.UTF8.GetBytes(str);