我正在做一个生成四个字节十六进制代码(例如12 12 12 12 12)的副项目,我得到了生成它的部分,但我希望能够使用它与任何长度的十六进制代码(例如12 12 12 12 12 12 12 12 12 12 12 12 12 12,基本上任何长度)我不知道如何,虽然,这是我现在的
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MetroFramework;
using MetroFramework.Forms;
namespace CodeGenerator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void copyoutputBytesbtn_Click(object sender, EventArgs e)
{
Clipboard.SetText(outputbytesTxtbox.Text);
}
private void copyfullCodebtn_Click(object sender, EventArgs e)
{
Clipboard.SetText(fullcodeTxtbox.Text);
}
private void inputBytestxtbox_TextChanged(object sender, EventArgs e)
{
if (inputBytestxtbox.Text.Contains(" "))
{
string inputBytes = inputBytestxtbox.Text.Replace(" ", String.Empty);
string f1 = inputBytes.Substring(0, 2);
string f2 = inputBytes.Substring(2, 2);
string f3 = inputBytes.Substring(4, 2);
string f4 = inputBytes.Substring(6, 2);
outputbytesTxtbox.Text = "0x" + f1 + " 0x" + f2 + " 0x" + f3 + " 0x" + f4;
//original format: 12 12 12 12//
//output format: 0x12 0x12 0x12 0x12//
}
}
}
}
我想能够使用任何长度的十六进制代码不只是四个,有什么方法我可以去做这个?
您可以使用for
loop:
static void Main(string[] args)
{
string input = "121212121212121"; // Your input form textblock
string[] result = SplitByTwo(input); // splitting the string
foreach (string s in result) // showing results
Console.Write($"{s} ");
}
public static string[] SplitByTwo(string input)
{
// the + 1 is here in case that the length is not divisible by 2
// examle: if length is 6 the array kength must be 3 | (6 + 1) / 2 = 3 (integer division)
// if length is 7 the array length must be 4 | (7 + 1) / 2 = 4
string[] output = new string[(input.Length + 1) / 2];
for (int i = 0; i < (input.Length + 1) / 2; i++)
{
if ((i * 2) + 1 == input.Length) // in case that the last split only contains 1 character
output[i] = input.Substring(i * 2, 1);
else
output[i] = input.Substring(i * 2, 2);
}
return output;
}
输出:
12 12 12 12 12 12 12 1
编辑:
如果你的输入有空格,你可以简单地把字符串分开,然后再连接起来:
string input = "12 12 12 12 12 12 12 1";
string output = "0x" + string.Join(" 0x", input.Split(' '));
Console.WriteLine(output);
输出:
0x12 0x12 0x12 0x12 0x12 0x12 0x12 0x1
请尝试下面的代码,并给我们反馈,如果它工作良好:
private void inputBytestxtbox_TextChanged(object sender, EventArgs e)
{
if (inputBytestxtbox.Text.Contains(" "))
{
const int step = 2;
string inputBytes = inputBytestxtbox.Text.Replace(" ", String.Empty);
StringBuilder sb = new StringBuilder();
for(int i = 0; i < inputBytes.Length; i+=step)
{
string fx = inputBytes.Substring(i, step);
sb.Append("0x");
sb.Append(fx);
if(i <= inputBytes.Length - step)
{
sb.Append(" ");
}
}
outputbytesTxtbox.Text = sb.ToString();
}
}