c# - 在 C# 中将字符串打印到字节指针

标签 c# c pointers translate

我正在尝试将 C 代码翻译为 C#,但我偶然发现了一行代码,但我在翻译时遇到了问题。

sprintf((char*)&u8FirmareBuffer[0x1C0] + strlen((char*)&u8FirmareBuffer[0x1C0]), ".B%s", argv[3]);

特别是这一行。 我猜 u8FirmwareBuffer 是 C 中的无符号字符数组,C# 中的字节数组。 argv[3] 是一个字符串。 我怎样才能将这一行翻译成 C#。

感谢您的帮助。

编辑:这已被标记为重复,但我认为它们有所不同,因为我使用的指针不适用于标记帖子上提供的解决方案。

最佳答案

你可以这样做:

string myString = "This is my string";
byte[] buffer = new byte[1024];
int offset = 0;

    // if you pass a byte buffer to the constructor of a memorystream, it will use that, don't forget that it cannot grow the buffer.
using (var memStream = new MemoryStream(buffer))
{
    // you can even seek to a specific position
    memStream.Seek(offset, SeekOrigin.Begin);

    // check your encoding..
    var data = Encoding.UTF8.GetBytes(myString);

    // write it on the current offset in the memory stream
    memStream.Write(data, 0, data.Length);
}
<小时/>

也可以使用 StreamWriter

string myString = "This is my string";
byte[] buffer = new byte[1024];
int offset = 0;

// if you pass a byte buffer to the constructor.....(see above)
using (var memStream = new MemoryStream(buffer))
using (var streamWriter = new StreamWriter(memStream))
{
    // you can even seek to a specific position
    memStream.Seek(offset, SeekOrigin.Begin);

    streamWriter.Write(myString);
    streamWriter.Flush();

    // don't forget to flush before you seek again
}              

关于c# - 在 C# 中将字符串打印到字节指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54179629/

相关文章:

c - linux的用户空间如何分配内存

代码在 Debug模式下工作正常,但在正常运行时失败

c - 为什么 {typedef int* PTR;const PTR p=#} 不等于 "const int* p=&num"而等于 "int *const p=&num"?

c# - 无法访问另一个命名空间中的继承类?

c# - Web API - 自关闭标记而不是 i :nil

c# - log4net 自定义日志记录

c - 这个表达式是如何求值的? (另外,那是什么?)

c - 如何在 C 中打乱数组

c++ - 如何在字符串的字符数组中使用++ 运算符访问下一个字符串?

c# - 初始化事件与检查 null