Chinaunix首页 | 论坛 | 博客
  • 博客访问: 16776
  • 博文数量: 18
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 170
  • 用 户 组: 普通用户
  • 注册时间: 2015-10-20 21:28
文章分类
文章存档

2015年(18)

我的朋友
最近访客

分类: C#/.net

2015-10-29 13:51:30


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]
}

阅读(448) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~