C# 中将数值型数据转换为字节数组的方法
private void value_bytearray()
{
double doublevalue = 258.0;
int32 intvalue = 258;
string strvalue = "258";
int16 int16value = 258;
memorystream doublemem = new memorystream();
binarywriter doublebytewr = new binarywriter(doublemem);
doublebytewr.write(doublevalue);
//doublemem.close();
binaryreader doublereader = new binaryreader(doublemem);
doublemem.seek(0, seekorigin.begin);
double heh = doublereader.readdouble();//heh确实是257.0
memorystream intmem = new memorystream();
binarywriter intbytewr = new binarywriter(intmem);
intbytewr.write(intvalue);
memorystream strmem = new memorystream();
binarywriter strbytewr = new binarywriter(strmem);
strbytewr.write(strvalue);
memorystream int16mem = new memorystream();
binarywriter int16bytewr = new binarywriter(int16mem);
int16bytewr.write(int16value);
byte[] bufferdouble = doublemem.toarray();
byte[] bufferint = intmem.toarray();
byte[] bufferint16 = int16mem.toarray();
byte[] bufferstr = strmem.toarray();
}
程序结果:
double =258.0 ;8位——0 0 0 0 0 32 112 64 字节数组
int32 = 258 ; 4——2 1 0 0
string ="258" ; 4——3 50 53 55
int16 = 258 ; 2——2 1
int16[] ={0,258,1} ;0 0 2 1 1 0
通过上面的例子,可以看出由数值型转换为字节数组后,程序是倒序读入的,但是读取的时候,vs会自动反转过来
int16[] int16array =new int16[3]{0,258,1} ;
memorystream int16mem = new memorystream();
binarywriter int16bytewr = new binarywriter(int16mem);
foreach (int16 hehe in int16array)
{
int16bytewr.write(hehe);
}
byte[] bufferint16 = int16mem.toarray();//0 0 2 1 1 0
binaryreader int16reader = new binaryreader(int16mem);
int16mem.seek(0, seekorigin.begin);
int16[] int16arraynew=new int16[3];
for (int i = 0; i < int16mem.length/2; i ++)
{
int16arraynew[i] = int16reader.readint16();//[0,258,1]
}
推荐阅读