BitConverter.GetBytes in place

后端 未结 5 865
-上瘾入骨i
-上瘾入骨i 2021-01-20 05:17

I need to get values in UInt16 and UInt64 as Byte[]. At the moment I am using BitConverter.GetBytes, but this method give

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-20 05:42

    BinaryWriter can be a good solution.

    var writer = new BinaryWriter(new MemoryStream(yourbuffer, youroffset, yourbuffer.Length-youroffset));
    writer.Write(someuint64);
    

    It's useful when you need to convert a lot of data into a buffer continuously

    var writer = new BinaryWriter(new MemoryStream(yourbuffer));
    foreach(var value in yourints){
        writer.Write(value);
    }
    

    or when you just want to write to a file, that's the best case to use BinaryWriter.

    var writer = new BinaryWriter(yourFileStream);
    foreach(var value in yourints){
        writer.Write(value);
    }
    

提交回复
热议问题