如何用你自己的字节创建字节数组?

时间:2014-02-06 11:21:26

标签: c# arrays hex bytearray

我必须创建自己的字节数组,例如:

byte[] connect = new byte[] { 0x00, 0x21, 0x60, 0x1F, 0xA1, 0x07 };

这个字节数组工作正常,但我需要更改一些十六进制代码。我尝试做了很多改变但是 没有人工作。

Int32 hex = 0xA1; 

byte[] connect = new byte[] { 0x00, 0x21, 0x60, 0x1F, 0xA1, hex};


string hex = "0xA1"; 

byte[] connect = new byte[] { 0x00, 0x21, 0x60, 0x1F, 0xA1, hex};


byte[] array = new byte[1];
array[0] = 0xA1;

byte[] connect = new byte[] { 0x00, 0x21, 0x60, 0x1F, 0xA1, array[0]};

我不知道我必须使用什么类型的变量来替换自动数组值。

2 个答案:

答案 0 :(得分:4)

将你的int转换为byte:

Int32 hex = 0xA1; 
byte[] connect = new byte[] { 0x00, 0x21, 0x60, 0x1F, 0xA1, (byte)hex};

或者将其定义为开头的字节:

byte hex = 0xA1; 
byte[] connect = new byte[] { 0x00, 0x21, 0x60, 0x1F, 0xA1, hex};

字符串到字节转换:

static byte hexstr2byte(string s)
{
    if (!s.StartsWith("0x") || s.Length != 4)
        throw new FormatException();
    return byte.Parse(s.Substring(2), System.Globalization.NumberStyles.HexNumber);
}

如您所见,.NET格式支持六位数,但不支持“0x”前缀。完全省略该部分会更容易,但你的问题并不完全清楚。

答案 1 :(得分:3)

声明它可能是“字节十六进制= 0xA1”吗?

相关问题