[英]How can I convert this method from C++ to C#?
有人可以解釋我如何將其寫入 C# 嗎?
//byte[] buffer is priavte in the class
//it's for writing Packets (gameserver)
void writeString(int location, std::string value, int length) {
if (value.length() < length) {
memcpy(&buffer[location], value.c_str(), value.length());
memset(&buffer[location+value.length()], 0, length-value.length());
}
else memcpy(&buffer[location], value.c_str(), length);
}
你的問題的確切答案是這樣的。 這是 C# class 中的私有方法(為清楚起見,我還添加了緩沖區字節數組):
byte[] buffer;
private void writeString(int location, string value, int length)
{
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
if (value.Length < length)
{
Array.Copy(encoding.GetBytes(value), 0, buffer, location, value.Length);
Array.Clear(buffer, location, length - value.Length);
}
else Array.Copy(encoding.GetBytes(value), 0, buffer, location, length);
}
C++ 到 C# 遷移指針:
查看 Buffer.BlockCopy
ASCIIEncoding.GetBytes
在腦海。 它將您的字符串作為參數並返回包含您的字符串的byte[]
緩沖區。
您是否嘗試將二進制數據寫入 stream、文件或類似文件? 如果是這樣,您可能最好使用BinaryWriter ,因為它本身支持序列化字符串(以及其他類型,就此而言)。
使用類似這樣的東西將字符串轉換為字節數組,然后使用 for 循環將這些字節放入作為消息緩沖區的字節數組中,並在必要時進行零填充
// C# to convert a string to a byte array.
public static byte[] StrToByteArray(string str)
{
System.Text.UTF8Encoding encoding=new System.Text.UTF8Encoding();
return encoding.GetBytes(str);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.