-3

这是我的代码,我只是想知道如何将 4bytes 拆分为 1byte-1byte-1byte-1byte

 static int count;
    private void SetClock_Click(object sender, EventArgs e)
    {

        count++;

        label5.Text = count.ToString("X8");

        DateTime time = DateTime.Now;
        txtSend.Text = "4D-" + "1A-" + "2B-" + "3C-" +
        (label5.Text.ToString()) + "-" + "03-" + "07-" + "00-" + 
        time.ToString("yy-MM-dd-") +
        ((int)time.DayOfWeek).ToString("00") +
        time.ToString("-HH-mm-ss");



        string[] allHaxValues = txtSend.Text.Split(new char[] { '-' });
        int result = 0;
        foreach (string haxValue in allHaxValues)
        {
            result = result ^ Convert.ToInt32(haxValue, 16);
        }
        //txtSend.Text = s;
        txtSend.Text = txtSend.Text + ("-") + result.ToString("X2");
     }

我在单击“00000001”时收到价值。我想像其他人一样得到它“00-00-00-01”谢谢

4

2 回答 2

2

您可以使用BitConverter该类将int值转换为xx-xx-xx-xx形式:

// make a four byte array of the int
byte[] parts = BitConverter.GetBytes(result);
// put the bytes in the right order
if (BitConverter.IsLittleEndian) {
  Array.Reverse(parts);
}
// turn the bytes into the xx-xx-xx-xx format
string resultString = BitConverter.ToString(parts);
于 2012-10-28T10:12:35.000 回答
0

基于@Guffa 解决方案:

private string IntToBytes(int count)
{ 
// make a four byte array of the int
byte[] parts = BitConverter.GetBytes(count);
// put the bytes in the right order
if (BitConverter.IsLittleEndian) {
  Array.Reverse(parts);
}
// turn the bytes into the xx-xx-xx-xx format
return BitConverter.ToString(parts);
}

现在只需更换

label5.Text = count.ToString("X8");

label5.Text = IntToBytes(count);
于 2012-10-28T10:33:48.210 回答