有没有那么痛苦的方式来GetBytes会不从0开始的缓冲区? [英] Is there a less painful way to GetBytes for a buffer not starting at 0?
本文介绍了有没有那么痛苦的方式来GetBytes会不从0开始的缓冲区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有处理项目中的原始字节,我需要基本上做这样的事情。
I am having to deal with raw bytes in a project and I need to basically do something like this
byte[] ToBytes(){
byte[] buffer=new byte[somelength];
byte[] tmp;
tmp=BitConverter.GetBytes(SomeShort);
buffer[0]=tmp[0];
buffer[1]=tmp[1];
tmp=BitConverter.GetBytes(SomeOtherShort);
buffer[2]=tmp[0];
buffer[3]=tmp[1];
}
我觉得这是错的但我找不到什么更好的方法的这样做。是否有更简单的方法?
I feel like this is so wrong yet I can't find any better way of doing it. Is there an easier way?
推荐答案
的BinaryWriter是非常有效的:
BinaryWriter is very efficient:
byte[] ToBytes() {
var ms = new MemoryStream(somelength);
var bw = new BinaryWriter(ms);
bw.Write(SomeShort);
bw.Write(SomeOtherShort);
return ms.ToArray();
}
这篇关于有没有那么痛苦的方式来GetBytes会不从0开始的缓冲区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文