C# 中將數值型資料轉換為位元組數組的方法

來源:互聯網
上載者:User

複製代碼 代碼如下: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]
}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.