问题描述
您好Codeproject。
我将结构数组列表转换为单字节数组时遇到问题。我需要这个转换,因为我必须使用ZLIB压缩列表。
这是我的列表:List< ST_Log> result = new List< ST_Log>();
结构如下所示:
Hi Codeproject.
I have a problem with converting an array list of structs to a single byte array. I need this convertion because i have to compress the list with ZLIB.
Here is my list: List<ST_Log> result = new List<ST_Log>();
And the struct look like this:
public struct ST_Log
{
public int ProjectId;
public int ChannelNumber;
public int Value;
public DateTime CreationTime;
public bool Delete;
public bool Invalid;
}
有没有人知道如何进行这种转换?
由Mik
Do any one have an idea of how to do this convertion?
By Mik
推荐答案
...
byte[] array = objectArray.SelectMany(a=> // select many should flatten the inner array so you get a 1d array. There are other ways to do this.
BitConverter.GetBytes(a.ProjectId) //bitconverter for ints
.Concat(BitConverter.GetBytes(a.ChannelNumber))
.Concat(BitConverter.GetBytes(a.Value))
.Concat(BitConverter.GetBytes(a.CreationTime.ToOaDate()))
.Concat(new[]{Convert.ToByte(a.Delete)}) //Convert.ToByte for bools as they are bits
.Concat(new[]{Convert.ToByte(a.Invalid)})).ToArray()
...
你可以转换因为你应该知道数据长度((32 + 32 + 32 + 32)/ 8 + 1 + 1)= 18
希望有帮助
You can de-convert because you should know the data length ((32+32+32+32)/8 + 1 + 1) = 18
Hope that helps
internal IEnumerable<ST_Log> DeconvertMany(byte[] converted)
{
//check that the byte is the correct length
if(converted.length % 18 != 0)
throw new exception("the byte is the wrong length");
for(int i = 0; i < converted.length / 18; i++){
byte[] single = converted.take(18); // take the first 18
converted = converted.skip(18); // remove the first 18 from the collection
yield DeconvertOne(single);
}
}
internal ST_Log DeconvertOne(byte[] converted){
int projectId = BitConverter.ToInt32(converted.take(4));
converted = converted.skip(4);
int channelNumber = BitConverter.ToInt32(converted.take(4));
converted = converted.skip(4);
int value = BitConverter.ToInt32(converted.take(4));
converted = converted.skip(4);
DateTime CreationTime = DateTime.FromOADate(BitConverter.ToInt32(converted.take(4)));
converted = converted.skip(4);
bool delete = Convert.ToBoolean(converted.take(1).Single();
converted = converted.skip(1);
bool invalid = Convert.ToBoolean(converted.take(1).Single();
return new ST_Log
{
ProjectId = projectId ,
ChannelNumber = channelNumber ,
Value = value ,
CreationTime = creationTime ,
Delete = delete ,
Invalid = invalid
}
}
我还没有测试过此代码所以可能需要一些调整
希望有帮助:)
I haven't tested this code so some tweaking may be required
Hope that helps :)
这篇关于将数组列表转换为单字节[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!