相当于 Java 的“ByteBuffer.putType()”在 C# 中

发布于 2024-08-02 09:01:28 字数 221 浏览 14 评论 0原文

我正在尝试通过从 Java 移植代码来格式化 C# 中的字节数组。在 Java 中,使用方法“buf.putInt(value);”、buf.putShort、buf.putDouble(等等)。但我不知道如何将其移植到 C#。我尝试过 MemoryStream 类,但没有方法将特定类型放在字节数组的末尾。

问题:C# 中 Java 的“ByteBuffer.putType(value)”相当于什么? 谢谢!

I am trying to format a byte array in C#, by porting a code from Java. In Java, the methods "buf.putInt(value);", buf.putShort, buf.putDouble, (and so forth) are used. However I don't know how to port this to C#. I have tried the MemoryStream class, but there is no method to put a specific type at the end of the byte array.

Question: What is the equivalent of Java's "ByteBuffer.putType(value)" in C#?
Thanks!

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

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

发布评论

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

评论(3

会发光的星星闪亮亮i 2024-08-09 09:01:28

您可以使用 BinaryWriter 和 MemoryStream:

MemoryStream stream = new MemoryStream();
using (BinaryWriter writer = new BinaryWriter(stream))
{
    writer.Write(myByte);
    writer.Write(myInt32);
    writer.Write("Hello");
}

byte[] bytes = stream.ToArray();

You can use a BinaryWriter and your MemoryStream:

MemoryStream stream = new MemoryStream();
using (BinaryWriter writer = new BinaryWriter(stream))
{
    writer.Write(myByte);
    writer.Write(myInt32);
    writer.Write("Hello");
}

byte[] bytes = stream.ToArray();
猛虎独行 2024-08-09 09:01:28

尝试 BinaryWriter班级:

using (var binaryWriter = new BinaryWriter(...))
{
    binaryWriter.Write(323);
    binaryWriter.Write(3487d);
    binaryWriter.Write("Hello");
}

Try the BinaryWriter class:

using (var binaryWriter = new BinaryWriter(...))
{
    binaryWriter.Write(323);
    binaryWriter.Write(3487d);
    binaryWriter.Write("Hello");
}
层林尽染 2024-08-09 09:01:28

您将需要使用 BitConverter 类。主要区别在于这些方法返回字节数组而不是更改现有数组。

(这是对提到的具体方法的替换;对于整个ByteBuffer类的替换,请参见其他回复。)

You'll be wanting to use the BitConverter class. The main difference is that these methods return an array of bytes instead of altering an existing array.

(This is a replacement for the specific methods mentioned; for a replacement of the entire ByteBuffer class, see the other replies.)

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