将字符串值的字符串数组转换为字节数组

时间:2012-05-16 09:40:09

标签: c# bytearray arrays

我在表单上有一个文本框,其中一个人以下面显示的格式输入一个字节数组。

我的问题是如何将生成的字符串数组转换为具有相同值的字节数组?

所以这将输入文本框:

0x11, 0x01, 0x49, 0x4D, 0x41, 0x47, 0x45, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x53, 0x75, 0x6D, 0x6D, 0x61, 0x72, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00

然后将以下代码拆分并将其转换为字节数组

string text = txtChecksumText.Text;
        string[] parts = text.Split(new string[] { ", " }, StringSplitOptions.None);
        byte[] bytes = new byte[parts.Length];

        for (int i = 0; i < parts.Length; i++)
        {
            bytes[i] = Convert.ToByte(parts[i], 16); // this isn't working as expected
            txtResponse.Text += Environment.NewLine + "     " + i + " = " + parts[i] + " = " + bytes[i].ToString() ;
        }

并且显示它的响应无效

 0 = 0x11 = 17
 1 = 0x01 = 1
 2 = 0x49 = 73
 3 = 0x4D = 77
 4 = 0x41 = 65
 5 = 0x47 = 71
 6 = 0x45 = 69
 7 = 0x31 = 49
 8 = 0x00 = 0
 9 = 0x00 = 0
 10 = 0x00 = 0
 11 = 0x00 = 0
 12 = 0x00 = 0
 13 = 0x00 = 0
 14 = 0x00 = 0
 15 = 0x00 = 0
 16 = 0x00 = 0
 17 = 0x00 = 0
 18 = 0x00 = 0
 19 = 0x00 = 0
 20 = 0x00 = 0
 21 = 0x00 = 0
 22 = 0x00 = 0
 23 = 0x01 = 1
 24 = 0x53 = 83
 25 = 0x75 = 117
 26 = 0x6D = 109
 27 = 0x6D = 109
 28 = 0x61 = 97
 29 = 0x72 = 114
 30 = 0x79 = 121
 31 = 0x00 = 0
 32 = 0x00 = 0
 33 = 0x00 = 0
 34 = 0x00 = 0
 35 = 0x00 = 0
 36 = 0x00 = 0
 37 = 0x00 = 0
 38 = 0x00 = 0
 39 = 0x00 = 0
 40 = 0x00 = 0
 41 = 0x00 = 0
 42 = 0x00 = 0
 43 = 0x00 = 0
 44 = 0x00 = 0
 45 = 0x00 = 0
 46 = 0x00 = 0
 47 = 0x00 = 0
 48 = 0x00 = 0
 49 = 0x00 = 0
 50 = 0x00 = 0
 51 = 0x00 = 0
 52 = 0x00 = 0
 53 = 0x00 = 0
 54 = 0x00 = 0
 55 = 0x00 = 0

为了清楚起见,0x11应该以字节11而不是字节17的形式返回,与其他所有其他我都没有尝试转换为十进制相同我试图将字面字节的字符串转换为字节数组用于创建支票金额

3 个答案:

答案 0 :(得分:2)

你得到的字节只是字节;它们本质上不是十进制或十六进制。

如果你想将字节传递给其他东西(用于校验和),它们就没问题了。

你唯一的问题是你是以十进制形式将它们写入控制台 - 如果你想以任何理由以十六进制形式写出它们,请使用ToString("x")

答案 1 :(得分:1)

请执行以下操作:

txtHexString.Text="0x11, 0x01, 0x49, 0x4D, 0x41, 0x47, 0x45, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x53, 0x75, 0x6D, 0x6D, 0x61, 0x72, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00";

string[] namesArray =  txtHexString.Text.Split(',');
byte[] abc= new byte [namesArray.Length];

for (int i = 0; i <= namesArray.Length - 1; i = i + 1)
        {
            abc[i] = Convert.ToByte(namesArray[i].Replace(" ", ""), 16);
        }

这里,abc是所需的字节数组。现在用abc做你想做的事。

答案 2 :(得分:0)

您的代码正常运行。切斯克此观察不同的转换并选择您需要的任何内容:

MessageBox.Show(11.ToString());
MessageBox.Show(11.ToString("x"));
MessageBox.Show(0x11.ToString());
MessageBox.Show(0x11.ToString("x"));
MessageBox.Show(BitConverter.ToString(new byte[] { 11, 0x11, 16 }));