我正在将小数转换为十六进制。用户将十进制数字键入到文本框中,并且有8个组合框,每个可能的位数一个。我编写的方法从文本框中获取输入字符串,并将十进制数转换为十六进制,然后将其作为字符串返回。
如何将返回的字符串(十六进制数)放入从“ cboHex0”到“ cboHex7”的正确组合框中,从最低有效位到MSB。
试过这个,但是不起作用。感谢所有帮助,因为我是Stackoverflow和C#的新手。
void decimalToHex(long dec)
{
if ((dec < 1) || (dec > 4294967295))
//if ((dec < 1) || (dec > 4294967295))
{
MessageBox.Show("ERROR\r\n" +
"Decimal number is not within the range for conversion");
return "0";
}
long hex = dec;
string hexStr = string.Empty;
while (dec > 0)
{
hex = dec % 16;
if (hex < 10)
hexStr = hexStr.Insert(0, Convert.ToChar(hex + 48).ToString());
else
hexStr = hexStr.Insert(0, Convert.ToChar(hex + 55).ToString());
dec /= 16;
}
//return hexStr;
//splitte streng til array.
string[] stringElements = hexStr.Split('');
stringElements.Reverse();
if (stringElements.Length > 0)
{
cboHex0.Text = stringElements[0];
}
if (stringElements.Length > 1)
{
cboHex1.Text = stringElements[1];
}
if (stringElements.Length > 2)
{
cboHex2.Text = stringElements[2];
}
if (stringElements.Length > 3)
{
cboHex3.Text = stringElements[3];
}
if (stringElements.Length > 4)
{
cboHex4.Text = stringElements[4];
}
if (stringElements.Length > 5)
{
cboHex5.Text = stringElements[5];
}
if (stringElements.Length > 6)
{
cboHex6.Text = stringElements[6];
}
if (stringElements.Length > 7)
{
cboHex7.Text = stringElements[7];
}
}
编辑:好的,看来我可以通过stringName [index]定位字符串中的字符。
因此,如果返回的字符串是“ 1AF”,我如何编码,以便8个组合框显示0,0,0,0,0,1,A,F?
首先,为了简化工作,使结果长度一致:
hexStr = hexStr.PadLeft(8, '0');
然后,您可以简单地分配以下框:
cboHex0.Text = hexStr.Substring(0,1);
cboHex1.Text = hexStr.Substring(1,1)
cboHex2.Text = hexStr.Substring(2,1);
等等
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句