所以我的課堂作業是讓我們自己的算法不使用將 int 轉換為十六進制的內置函數,並且在我的生活中它不會遵守。
我們文本中的示例將 24032 轉換為 0x5DE0,但我得到的輸出是 3210。
這是我的代碼
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
List<string> errorList = new List<string>();
List<int> hexList = new List<int>();
string intInput = "";
string msgOutput = "";
private void btn_Hex_Click(object sender, EventArgs e)
{
intInput = box_Int.Text;
int toHexFunc = Validator(intInput);
ToHex(toHexFunc);
}
public void ToHex(int fromHexBtn)
{
int n = fromHexBtn;
char[] hexNum = new char[100];
int i = 0;
while (n != 0)
{
int iterTemp = n % 16;
// using ASCII table from https://www.dotnetperls.com/ascii-table
if (iterTemp < 10)
{
hexNum[i] = (char)(iterTemp + 48);
i++;
}
else
{
hexNum[i] = (char)(iterTemp + 55);
i++;
}
n = n / 16;
}
for (int j = i - 1; j >= 0; j--)
{
hexList.Add(j);
}
msgOutput = String.Join("", hexList);
lbl_Message.Text = msgOutput;
}
}
基於此https://www.permadi.com/tutorial/numDecToHex/
class Program
{
static void Main(string[] args)
{
var characters = "0123456789ABCDEF";
int number = 24032;
var hexidecimal = "";
while (number > 0)
{
var remainder = number % 16;
var res = Math.Abs(number / 16);
hexidecimal = characters[remainder] + hexidecimal;
number = res;
}
hexidecimal = "0x" + hexidecimal;
WriteLine(hexadecimal);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句