2013-10-28 49 views
0

我想寫入一個字節數組。我不知道如何處理文本部分。需要幫助在C編寫字符串到十六進制#

實施例: 設置與值TEST命名的字母數字的變量:

[0×02] [0×00] [0x35] [0×37] [0xFF的] [0×00] =試驗的[0×00] [0×03]

我知道如何用給定的十六進制在上面的例子,但是,當我到達=考驗,我需要知道如何它放到字節數組。

byte[] byteData = {0x02, 0x00, 0x35, 0x37, 0xFF, What do I do here?, 0x00, 0x03}; 
+3

如何*應*它寫? – user2864740

+0

總之,使用['MemoryStream'(http://msdn.microsoft.com/en-us/library/system.io.memorystream.aspx)可以簡化這個任務(寫前綴,根據規則寫「TEST」 ,寫後綴,使用'ms.ToArray()')。或者,查看'IEnumerable.Concat'可以提供幫助。 – user2864740

+0

確定編碼的二進制數據來從文本字節[]。 E.g如果ASCII使用Encoding.ASCII.GetBytes(...),以獲得從字符串一個byte []。 – SpaceghostAli

回答

1

像這樣的事情會做你:

byte[] octets ; 
Encoding someEncoding = new UTF8Encoding(false) ; 

using(MemoryStream aMemoryStream = new MemoryStream(8192)) // let's start with 8k 
using (BinaryWriter writer = new BinaryWriter(aMemoryStream , someEncoding)) // wrap that puppy in a binary writer 
{ 
    byte[] prefix = { 0x02 , 0x00 , 0x35 , 0x37 , 0xFF , } ; 
    byte[] suffix = { 0x00 , 0x03 , } ; 

    writer.Write(prefix) ; 
    writer.Write("OF=TEST"); 
    writer.Write(suffix) ; 

    octets = aMemoryStream.ToArray() ; 

} 

foreach (byte octet in octets) 
{ 
    Console.WriteLine("0x{0:X2}" , octet) ; 
} 
+0

謝謝,這正是我一直在尋找的。 –

1
byte[] preByteData = {0x02, 0x00, 0x35, 0x37, 0xFF}; 
byte[] postByteData = {0x00, 0x03}; 
//using System.Linq; 
byte[] byteData = preByteData.Concat(System.Text.Encoding.UTF8.GetBytes("OF=TEST").Concat(postByteData)).ToArray(); 
相關問題