[英]How you can represent binary numbers on label?
I converted decimal to binary number however i dont know how to represent on label. 我将十进制转换为二进制数,但是我不知道如何在标签上表示。 I have a list of numbers 0 and 1,Now, how do I display the information on labels.In fact, i dont know how to represent on label.
我有一个数字0和1的列表,现在,如何在标签上显示信息。实际上,我不知道如何在标签上表示。
private void btnRun_Click(object sender, EventArgs e)
{
var decimaltoBinary = fnDecimalToBinary(Convert.ToInt32(txtenterNumber.Text));
}
private List<int> fnDecimalToBinary(int number)
{
int[] decimalNumbers = new int[] { 1, 2, 4, 8, 16, 32, 64, 128, 256 };
List<int> binaryNumbers = new List<int>();
int locDecimalArray = 0;
int sumNumber = 0;
for (int i = 0; i < decimalNumbers.Length; i++)
{
if (number < decimalNumbers[i])
{
sumNumber = number;
locDecimalArray = i - 1;
for (int j = locDecimalArray; j >= 0; j--)
{
if (sumNumber == 0)
{
binaryNumbers.Add(0);
return binaryNumbers;
}
else if (sumNumber >= decimalNumbers[j])
{
sumNumber = sumNumber - decimalNumbers[j];
binaryNumbers.Add(1);
}
else if (sumNumber < decimalNumbers[j])
{
binaryNumbers.Add(0);
}
}
return binaryNumbers;
}
}
return binaryNumbers;
}
It seems that you've received a comment that explains how you can convert your List<int>
to the string
value you need for the Label
control. 看来您已经收到一条评论,解释了如何将
List<int>
转换为Label
控件所需的string
值。 However, it seems to me that for the purposes of this exercise, you might benefit from some help with the decimal-to-binary conversion itself. 但是,在我看来,就本练习而言,您可能会受益于十进制到二进制转换本身的一些帮助。 There are already a number of similar questions on Stack Overflow dealing with this scenario (as you can guess, converting to binary text is a fairly common programming exercise), but of course none will start with your specific code, so I think it's worth writing yet another answer.
关于这种情况,Stack Overflow上已经存在许多类似的问题(您可以猜到,转换为二进制文本是相当普遍的编程工作),但是当然没有一个会从您的特定代码开始,因此我认为值得编写还有一个答案。 :)
:)
Basing the conversion on a pre-computed list of numeric values is not a terrible way to go, especially for the purposes of learning. 将转换基于预先计算的数值列表并不是一个糟糕的方法,特别是出于学习目的。 But your version has a bunch of extra code that's just not necessary:
但是您的版本有很多额外的代码,这些代码是不必要的:
0
is always less than any of the digit values you've pre-computed, so there's no need to check for that explicitly. 0
始终小于您预先计算的任何数字值,因此无需显式检查。 You really only need the if
and a single else
inside the inner loop. if
和一个else
。 for
loops are generally more readable when they start at 0
and increment the index as opposed to starting at the end and decrement, it seems to me that you would be better off writing the pre-computed values in reverse. for
循环通常从0
开始并增加索引而不是从末尾开始递减,因此通常更具可读性,在我看来,最好编写pre-反向计算值。 static
field, and then just using whatever subset of that you need, would be yet another suitable approach). static
字段中,然后仅使用所需的任何子集,这将是另一种合适的方法)。 With those changes, you would get something like this: 进行这些更改后,您将获得以下内容:
private List<int> DecimalToBinary(int number, int digitCount)
{
// The number can't itself have more than 32 digits, so there's
// no point in allowing the caller to ask for more than that.
if (digitCount < 1 || digitCount > 32)
{
throw new ArgumentOutOfRangeException("digitCount",
"digitCount must be between 1 and 32, inclusive");
}
long[] digitValues = Enumerable.Range(0, digitCount)
.Select(i => (long)Math.Pow(2, digitCount - i - 1)).ToArray();
List<int> binaryDigits = new List<int>(digitCount);
for (int i = 0; i < digitValues.Length; i++)
{
if (digitValues[i] <= number)
{
binaryDigits.Add(1);
number = (int)(number - digitValues[i]);
}
else
{
binaryDigits.Add(0);
}
}
if (number > 0)
{
throw new ArgumentOutOfRangeException("digitCount",
"digitCount was not large number to accommodate the number");
}
return binaryDigits;
}
And here's an example of how you might use it: 这是一个如何使用它的示例:
private void button1_Click(object sender, EventArgs e)
{
int number;
if (!int.TryParse(textBox1.Text, out number))
{
MessageBox.Show("Could not convert user input to an int value");
return;
}
try
{
List<int> binaryDigits = DecimalToBinary(number, 8);
label3.Text = string.Join("", binaryDigits);
}
catch (ArgumentOutOfRangeException e1)
{
MessageBox.Show("Exception: " + e1.Message, "Could not convert to binary");
}
}
Now, the above example fits the design you originally had, just cleaned it up a bit. 现在,上面的示例适合您最初的设计,只是对其进行了一些整理。 But the fact is, the computer already knows binary.
但事实是,计算机已经知道二进制文件。 That's how it stores numbers, and even if it didn't, C# includes operators that treat the numbers as binary (so if the computer didn't use binary, the run-time would be required to translate for you anyway).
这就是它存储数字的方式,即使不存储数字,C#也会将数字视为二进制的运算符(因此,如果计算机不使用二进制,则无论如何都需要运行时为您转换)。 Given that, it's actually a lot easier to convert just by looking at the individual bits.
鉴于此,仅查看各个位实际上就容易得多。 For example:
例如:
private List<int> DecimalToBinary2(int number, int digitCount)
{
if (digitCount < 1 || digitCount > 32)
{
throw new ArgumentOutOfRangeException("digitCount",
"digitCount must be between 1 and 32, inclusive");
}
if (number > Math.Pow(2, digitCount) - 1)
{
throw new ArgumentOutOfRangeException("digitCount",
"digitCount was not large number to accommodate the number");
}
List<int> binaryDigits = new List<int>(digitCount);
for (int i = digitCount - 1; i >= 0; i--)
{
binaryDigits.Add((number & (1 << i)) != 0 ? 1 : 0);
}
return binaryDigits;
}
The above simply starts at the highest possible binary digit (given the desired count of digits), and checks each individual digit in the provided number, using the "bit-shift" operator <<
and the logical bitwise "and" operator &
. 上面的代码简单地从最高可能的二进制数字开始(给定所需的位数),并使用“ bit-shift”运算符
<<
和逻辑按位“ and”运算符&
检查提供的数字中的每个数字。 If you're not already familiar with binary arithmetic, shift operations, and these operators, this might seem like overkill. 如果您还不熟悉二进制算术,移位运算和这些运算符,这似乎有点过头了。 But it's actually a fundamental aspect of how computers work, worth knowing, and of course as shown above, can dramatically simplify code required to deal with binary data (to the point where parameter validation code takes up half the method :) ).
但这实际上是计算机工作方式的一个基本方面,值得了解,当然如上所述,它可以大大简化处理二进制数据所需的代码(以至于参数验证代码只占方法的一半:)。
One last thing: this entire discussion ignores the fact that you're using a signed int
value, rather than the unsigned uint
type. 最后一件事:整个讨论都忽略了您使用带符号的
int
值而不是无符号的uint
类型这一事实。 Technically, this means your code really ought to be able to handle negative numbers as well. 从技术上讲,这意味着您的代码确实也应该能够处理负数。 However, doing so is a bit trickier when you also want to deal with binary digit counts that are less than the natural width of the number in the numeric type (eg 32 bits for an
int
). 但是,当您还想处理小于数字类型数字的自然宽度(例如32位
int
)的二进制数字计数时,这样做会有些棘手。 Conversely, if you don't want to support negative numbers, you should really be using the uint
type instead of int
. 相反,如果您不希望支持负数,则应该使用
uint
类型而不是int
类型。
I figured that trying to address that particular complication would dramatically increase the complexity of this answer and take away from the more fundamental details that seemed worth conveying. 我认为,尝试解决该特定的复杂性将大大增加该答案的复杂性,并摆脱似乎值得传达的更基本的细节。 So I've left that out.
因此,我将其省略。 But I do encourage you to look more deeply into how computers represent numbers, and why negative numbers require more careful handling than the above code is doing.
但是,我确实鼓励您更深入地研究计算机如何表示数字,以及为什么负数需要比上述代码更仔细地处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.