我如何更改此代码以便它写入字符串?

发布于 2024-12-01 10:34:13 字数 778 浏览 2 评论 0原文

你好,我有这部分代码:

static void Main(string[] args)
{
    Console.WriteLine("Memory mapped file reader started");

    using (var file = MemoryMappedFile.OpenExisting("sensor"))
    {
        using (var reader = file.CreateViewAccessor(0, 3800))
        {
            var bytes = new byte[4051];

            Console.WriteLine("Reading bytes");
            for (var i = 0; i < bytes.Length; i++)
                Console.Write((char)bytes[i] + "");

            Console.WriteLine(string.Empty);
        }
    }

    Console.WriteLine("Press any key to exit ...");
    Console.ReadLine();
}

它打开共享内存,然后将其写入 var bytes 并显示它。我该如何将其写入字符串?我知道它与“var bytes = new byte[4051];”有关但显然我无法将“byte”写入新字符串。

PS 现在代码的输出(带有数组)是简单的文本:ABCDEFG...等

谢谢

hello i have this part of my code:

static void Main(string[] args)
{
    Console.WriteLine("Memory mapped file reader started");

    using (var file = MemoryMappedFile.OpenExisting("sensor"))
    {
        using (var reader = file.CreateViewAccessor(0, 3800))
        {
            var bytes = new byte[4051];

            Console.WriteLine("Reading bytes");
            for (var i = 0; i < bytes.Length; i++)
                Console.Write((char)bytes[i] + "");

            Console.WriteLine(string.Empty);
        }
    }

    Console.WriteLine("Press any key to exit ...");
    Console.ReadLine();
}

which opens the shared memory and then writes it to var bytes and displays it. how would i instead write it to a string? i know it has something to do with "var bytes = new byte[4051];" but i cant write "byte" to a new string obviously.

PS the output of the code now(with the array) is simple text: ABCDEFG... etc

thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

疯狂的代价 2024-12-08 10:34:13

如果您要写入的是文本信息,只需选择编码,然后对数据使用 GetString 即可。

 var encoding = Encoding.ASCII;
 Console.WriteLine(encoding.GetString(bytes));

如果您想以文本方式显示二进制数据(如十六进制),那么您将需要扩展方法或以其他方式对其进行转换。

static string ToHex(this byte[] data) {
    var builder = new StringBuilder(data.Length * 3);
    foreach (var b in data)
        buidler.Append(b.ToString("X2") + " ");
    return builder.ToString();
}

....

Console.WriteLine(bytes.ToHex());

If it's textual information you're trying to write, just pick encoding, and use GetString on the data.

 var encoding = Encoding.ASCII;
 Console.WriteLine(encoding.GetString(bytes));

If it's binary data you want to display textually (as in hex), then you'll need an extension method or otherwise to convert it.

static string ToHex(this byte[] data) {
    var builder = new StringBuilder(data.Length * 3);
    foreach (var b in data)
        buidler.Append(b.ToString("X2") + " ");
    return builder.ToString();
}

....

Console.WriteLine(bytes.ToHex());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文