Pit*_*erK 3 c# floating-point byte memorystream
我想创建一个包含int32,int16,单值的内存流.使用二进制文件是没用的,所以我试图创建字节数组.因为值是不同的类型,我不知道如何正确地做到这一点.所以我尝试这样做:
byte[] tab = new byte[]{2,0,0,0,3,0,3,0} - 2是int32(四个字节),另外两个是int16(两个字节)
工作正常,但是当我想添加一些单个值时,它会产生错误.我不能这样做:
byte[] tab = new byte[]{2,0,0,0,3,0,3,0,4.4f,5.6f}
我必须有正确格式的流,因为这个流将在这个方法中读取:
short[] rawData;
float[] modulusData;
public void rawData(Stream s)
{
BinaryReader br = new BinaryReader(s);
int dataCount = br.ReadInt32();
if (dataCount > 0)
{
rawData = new short[dataCount];
for (int i = 0; i < dataCount; i++)
rawData[i] = br.ReadInt16();
}
else
rawData = new short[0];
dataCount = br.ReadInt32();
if (dataCount > 0)
{
modulusData = new float[dataCount];
for (int i = 0; i < dataCount; i++)
modulusData[i] = br.ReadSingle();
}
else
modulusData = new float[0];
}
Run Code Online (Sandbox Code Playgroud)
任何人都知道如何做到这一点?
相反,你原来的说法,BinaryWriter是正是你想要的.这就是它的设计目标.特别是,如果你BinaryReader以后再使用它是完全合适的.
你没有说明为什么你不想使用它,但它确实是你应该使用的:
using (MemoryStream stream = new MemoryStream())
{
using (BinaryWriter writer = new BinaryWriter(stream))
{
writer.Write(2);
writer.Write((short) 3);
writer.Write((short) 3);
writer.Write(4.4f);
writer.Write(5.6f);
}
byte[] bytes = stream.ToArray();
}
Run Code Online (Sandbox Code Playgroud)
这将生成一个包含以下数据的字节数组:
[Int32 ] [Int16] [Int16] [Single ] [Single ]
02 00 00 00 03 00 03 00 CD CC 8C 40 33 33 B3 40
Run Code Online (Sandbox Code Playgroud)
需要注意的一点 - 您的写作描述会写下这些值:
- Int32
- Int16
- Int16
- Single
- Single
Run Code Online (Sandbox Code Playgroud)
...但您的阅读代码将为:
- Int32 (value 2)
- Int16
- Int16
- Int32 (this wasn't written - so you're reading data from the first Single!)
- ???
Run Code Online (Sandbox Code Playgroud)
换句话说,如果您以前的尝试BinaryWriter失败,因为它们看起来像我的初始代码,那是因为您忘记了
writer.Write(2);
Run Code Online (Sandbox Code Playgroud)
在写入Int16值之后,说出存在多少单个值.
请注意,如果您不需要将值作为字节数组,则无需调用ToArray- 只需返回流(不会丢弃它).但是,在阅读之前,您需要"回放"它.例如:
public Stream GetData()
{
MemoryStream stream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(stream); // Don't close at the end!
writer.Write(2);
writer.Write((short) 3);
writer.Write((short) 3);
writer.Write(2); // Extra count for the Single values
writer.Write(4.4f);
writer.Write(5.6f);
writer.Flush(); // May not be required...
stream.Position = 0; // Rewind so stream can be read again
return stream;
}
Run Code Online (Sandbox Code Playgroud)