需要帮助在C#中将字符串写入HEX

时间:2013-10-28 19:04:19

标签: c# hex

我正在尝试将其写入字节数组。我不知道如何处理文本部分。

示例: 设置名为OF的字母数字变量,其值为TEST:

[0×02] [0×00] [0x35] [0×37] [0xFF的] [0×00] =试验的[0×00] [0×03]

我知道如何在上面的例子中编写给定的十六进制,但是,当我进入OF = TEST时,我需要知道如何将其放入字节数组中。

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

2 个答案:

答案 0 :(得分: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 ) ;
}

答案 1 :(得分: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();