2011-05-02 126 views
0

嗨需要幫助該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

回答

2
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);