这是我的代码,我只想知道如何将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”谢谢
答案 0 :(得分: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);
答案 1 :(得分: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);