MemoryStream:为什么在readByte之后转换为byte

发布于 2024-11-26 19:24:36 字数 588 浏览 0 评论 0原文

MS 的这个示例中,您会注意到在我们读取一个字节后从内存流中,它进入一个 int,然后必须将其转换为 byte。让我感到奇怪的是,像 .ReadByte() 这样的函数一开始就不返回字节。 MS这样做有什么原因吗?

// Read the remaining bytes, byte by byte.
while(count < memStream.Length)
{
    byteArray[count++] =
        Convert.ToByte(memStream.ReadByte());
}

我想到了一个想法。也许这取决于使用情况。也许ReadByte()经常用于检索短长度,随后在通过长度变化的检索中消耗它

int length=ms.ReadByte();
ms.Read(buf,0,lenth);

,即您可以使用不进行强制转换的长度。这是一个足够好的理由吗?

In this example from MS, you'll notice that after we read a byte from memory stream, it goes into an int which must then be converted to byte. It stikes me as strange that a function like .ReadByte() doesn't return a byte in the first place. Is there a reason why MS did it this way?

// Read the remaining bytes, byte by byte.
while(count < memStream.Length)
{
    byteArray[count++] =
        Convert.ToByte(memStream.ReadByte());
}

a thought occured to me. Perhaps this comes down to usage. Perhaps ReadByte() is often used to retrieve short lengths, which subsequents get consumed in the retrieve via length variety

int length=ms.ReadByte();
ms.Read(buf,0,lenth);

i.e. you can use the length without a cast. Is this a good enough reason?

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

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

发布评论

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

评论(3

分開簡單 2024-12-03 19:24:36

这并不是Memory Stream特有的,而是因为基类“Stream”的设计,其原因是

返回值:

无符号字节转换为 Int32,如果位于流末尾,则为 -1。

-1不能用无符号字节表示

This is not specific to Memory stream, rather it is because of the design of base class "Stream" and the reason for that is

Return value:

The unsigned byte cast to an Int32, or -1 if at the end of the stream.

-1 cannot be represented using unsigned byte

还不是爱你 2024-12-03 19:24:36

当您使用ReadByte时,如果读取成功,则流中的当前位置将前进一个字节。但它的设计是如果到达流末尾则返回 -1。

现在,这将不是 Byte 的有效值(其无符号)

ms.Read(buf,0,lenth); 这里 lenth 是要从流,你从 ReadByte 得到的是第一个字节,它不能以这种方式使用,比如

byte[] buff = new byte[ms.Length];
ms.Read(buff , 0, buff .Length);

When you use ReadByte If the read is successful then the current position within the stream is advanced by one byte. but its designed to return -1 if the end of the stream has been reached.

Now this would not be a valid value for Byte (its unsigned)

ms.Read(buf,0,lenth); here lenth is the number of bytes to read from the stream and what you get from ReadByte is first byte its not be used in the this fashion, something like

byte[] buff = new byte[ms.Length];
ms.Read(buff , 0, buff .Length);
夢归不見 2024-12-03 19:24:36

我确实相信他们正在以一种非常好的方式从 int 转换为 byte,因为 ReadByte() 返回一个 int 和他们的 byteArray 的类型为 int[]

I do believe they are converting with that from int to byte in a reallllllly nice way, since ReadByte() returns an int and their byteArray is of type int[].

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