简体   繁体   English

将带符号的字节数组写入流

[英]Write signed byte array to a stream

I want to write signed byte array sbyte[] to a stream. 我想将有符号字节数组sbyte[]写入流。 I know that Stream.Write accepts only unsigned byte[], so I could convert sbyte[] to byte[] prior to passing it to the stream. 我知道Stream.Write只接受unsigned byte [],所以我可以在将sbyte[]传递给stream之前将其转换为byte[] But I really need to send the data as sbyte[] . 但我真的需要以sbyte[]发送数据。 Is there some way to do it? 有办法吗? I found BinaryWriter.Write but is this equivalent to Stream.Write ? 我找到了BinaryWriter.Write但这相当于Stream.Write

You can use the fact that the CLR allows you to convert between byte[] and sbyte[] "for free" even though C# doesn't: 您可以使用CLR允许您在byte[]sbyte[] “之间免费转换”这一事实,即使C#没有:

sbyte[] data = ...;
byte[] equivalentData = (byte[]) (object) data;
// Then write equivalentData to the stream

Note that the cast to object is required first to "persuade" the C# compiler that the cast to byte[] might work. 请注意,首先需要强制转换为object以“说服”C#编译器,转换为byte[] 可能会起作用。 (The C# language believes that the two array types are completely incompatible.) (C#语言认为这两种数组类型完全不兼容。)

That way you don't need to create a copy of all the data - you're still passing the same reference to Stream.Write , it's just a matter of changing the "reference type". 这样您就不需要创建所有数据的副本 - 您仍然将相同的引用传递给Stream.Write ,只需更改“引用类型”即可。

Some Background: 一些背景:

An unsigned Byte has 8 Bits and can represent values between 0 and 255. 无符号字节有8个位,可以表示0到255之间的值。

A signed Byte is the same 8 Bits but interpreted differently: the leftmost Bit (MSB) is considered a "sign" Bit with 0 meaning positive, 1 meaning negative. 符号的字节是相同的8位,但解释不同:最左边的位(MSB)被认为是“符号”位,0表示正,1表示负。 The remaining 7 Bites may represent a value between 0 and 127. 其余7个Bites可以表示0到127之间的值。

Combined a unsigned Byte may represent a value between -128 and +127 组合无符号字节可以表示-128和+127之间的值

If you send such a byte over the wire (the network) it is up to the receiver to interpret it correctly. 如果您通过线路(网络)发送这样的字节,接收可以正确解释它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM