在C#中将IByteBuffer转换为字符串。

huangapple go评论78阅读模式
英文:

Convert IByteBuffer to String in C#

问题

I want to convert IByteBuffer value to the String.

英文:

I am working on existing project which is built using DotNetty library, mostly networking framework. I am not that much aware with this framework but as a quick fix, I want to convert IByteBuffer value to the String.

答案1

得分: 1

IByteBuffer 表示各种数据类型的二进制数据流,而不是字符串。

如果您想要获取缓冲区中所有字节的转储,可以使用 ByteBufferUtil.HexDump。这会给您一个以十六进制表示的单个字节的字符串。如果缓冲区的数据不如您所期望的那样,这在故障排除时非常有用 - 您可以逐个字节地追踪数据,找出问题所在。

如果您想以不同的方式解释这些字节,您真的需要了解缓冲区中的数据类型。没有通用的方法,因为缓冲区不是自描述的(不像 XML 那样)。如果您想快速查看缓冲区中的字符串数据,并且数据恰好是用 ASCII 编码的,您可以尝试类似以下的方法:

Encoding.ASCII.GetString(byteBuffer.Array)

不用说,除非整个缓冲区包含 ASCII 字符串,否则这将产生大量垃圾数据。这是否有用完全取决于您正在处理的数据;如果缓冲区包含类似 HTTP 请求的内容,您可能会看到数据正常。不用说,这仅应用于调试目的 - 对于任何生产用途,您应该真正了解缓冲区的布局,而不是猜测它。

英文:

IByteBuffer represents a stream of binary data of various data types, not a string.

If you want a dump of all the bytes in the buffer, you can use ByteBufferUtil.HexDump. This gives you a string of the individual bytes in hexadecimal. This is useful for troubleshooting, if the buffer doesn't contain quite the data you are expecting - you can go tracing the data byte by byte, and find where it goes wrong.

If you want to interpret the bytes differently, you really need to know the types in the buffer. There's no generic method, because the buffer isn't self-descriptive (unlike e.g. XML). If you're trying to get a quick look at the string data in the buffer, and the data happens to be encoded in ASCII, you can try something like this:

Encoding.ASCII.GetString(byteBuffer.Array)

Needless to say, unless the whole buffer contains an ASCII string, this will produce lots of garbage. Whether this is useful or not depends entirely on the data you're working with; if the buffer has something like an HTTP request, you'll probably see the data just fine. Needless to say, this should only be used for debugging purposes - for any production use, you should really know the layout of the buffer explicitly, rather than guessing at it.

huangapple
  • 本文由 发表于 2020年1月6日 15:24:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/59608165.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定