简体   繁体   English

如何在标签上表示二进制数字?

[英]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: 但是您的版本有很多额外的代码,这些代码是不必要的:

  1. Your outer loop doesn't accomplish anything except verify that the number passed is within the range permitted by your pre-computed values. 除了验证传递的数字是否在预先计算的值允许的范围内之外,您的外循环什么也没做。 But this can be done as part of the conversion itself. 但这可以作为转换本身的一部分来完成。
  2. Furthermore, I'm not convinced that returning an empty list is really the best way to deal with invalid input. 此外,我不认为返回一个空列表确实是处理无效输入的最佳方法。 Throwing an exception would be more appropriate, as this forces the caller to deal with errors, and allows you to provide a textual message for display to the user. 引发异常会更合适,因为这会强制调用者处理错误,并允许您提供文本消息以显示给用户。
  3. The value 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
  4. Since you are the one populating the array, and since 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-反向计算值。
  5. Entering numbers by hand is a pain and it seems to me that the method could be more flexible (ie support larger binary numbers) if you allowed the caller to pass the number of digits to produce, and used that to compute the values at run-time (though, if for performance reasons that's less desirable, pre-computing the largest digits that would be used and storing that in a 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.

相关问题 枚举可以表示字符串数字吗? - Can enum represent string numbers? 你能比较存储为字符串的两个数字而不知道它们代表的数据类型吗? - Can you compare two numbers stored as strings without knowing the datatype they represent? 如果不能容纳足够多的有效数字,那么双精度数如何代表比小数更高的数字? - How can doubles represent higher numbers than decimals if they can't hold as many significant figures? 如何使用按钮和文本框更改标签? - How can you use a button and a text box to change a label? 如何将 Label 绑定到 function 结果为 Xamarin.Z645024253191292AE688A8A - How can you bind a Label to a function result in Xamarin.Forms 如何删除图表区域下的按键标签? - How can you remove label of key under chart area? 如何将列表项拖放到标签上,使其成为C#中标签的文本? - How can you drag and drop a list item to a label so it's the label's text in C#? 如何在C#中用8位表示4位二进制数? - How to represent a 4 bit binary number with 8 bits in C#? 您能用Google的协议缓冲区格式表示CSV数据吗? - Can you represent CSV data in Google's Protocol Buffer format? 表示数字序列的算法 - Algorithm to represent a sequence of numbers
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM