Home > OS >  from binary to decimal with process too
from binary to decimal with process too

Time:11-08

Change for example 10100 to decimal and here is how

= (1x2)^4   (0x2)^3   (1x2)^2   (0x2)^1   (0x2)^ 0

= 16   0   4   0   0

= 20

Okay I understand the way to convert yet I want to the output not only showing "20" but like :

Enter binary : 10100

(1x2)^4 (0x2)^3 (1x2)^2 (0x2)^1 (0x2)^ 0

16 0 4 0 0

20

This is my try and the output is not what i want

String input = Console.ReadLine();
            char[] array = input.ToCharArray();

            int npower = array.Length;
            npower--;
            int npower1 = array.Length;
            npower1--;
            // Reverse since 16-8-4-2-1 not 1-2-4-8-16. 
            Array.Reverse(array);
            // Reverse since 16-8-4-2-1 not 1-2-4-8-16. 

            /*
             * [0] = 1
             * [1] = 2
             * [2] = 4
             * etc
             */
            int sum = 0;
            int i = 0;
            for (i=0; i < array.Length; i  )
            {
                if (array[i] == '1')
                {
                    // Method uses raising 2 to the power of the index. 
                    if (i == 0)
                    {
                        sum  = 1;
                    }
                    else
                    {
                        sum  = (int)Math.Pow(2, i);
                    }
                }
                Console.Write("("   array[i] "*2)^" npower);
                npower--;
                if (npower > -1)
                {
                    Console.Write("   ");
                }
                
            }
            Console.WriteLine();
            for (i = 0; i < array.Length; i  )
            {
                Console.Write(" "   array[i] * (int)Math.Pow(2, npower1)   "");
                npower1--;
                if (npower1 > -1 )
                {
                    Console.Write("   ");
                }
            }
            
            Console.WriteLine();
            Console.WriteLine(" = " sum);
            Console.ReadLine();
      

The output from the code:

10100
(0*2)^4   (0*2)^3   (1*2)^2   (0*2)^1   (1*2)^0
768    384    196    96    49
= 20

Okay the convert result is correct but the step in reverse

The output should be like

10100
(1*2)^4   (0*2)^3   (1*2)^2   (0*2)^1   (0*2)^0
16    0    4    0    0
= 20

The question is how to implement the output i want please

CodePudding user response:

I suggest quering input string with a help of Linq and get all three required strings (note, I've used 1 << n instead of (int)Math.Pow(2, n)):

using System.Linq;

...
//TODO: When using Console.ReadLine() don't forget to validate input
// e.g. input.Length > 0 && input.Length <= 31 && 
//      input.All(c => c == '0' || c == '1')
string input = "10100";

string first = string.Join("   ",
  input.Select((value, index) => $"({value - '0'}*2)^{input.Length - index - 1}"));

string second = string.Join("   ",
  input.Select((value, index) => (value - '0') * (1 << (input.Length - index - 1))));

string third = $"= {input.Aggregate(0, (s, a) => s * 2   a - '0')}";

Let's have a look:

Console.WriteLine(first);
Console.WriteLine(second);
Console.WriteLine(third);

Output:

(1*2)^4   (0*2)^3   (1*2)^2   (0*2)^1   (0*2)^0
16   0   4   0   0
= 20

CodePudding user response:

Three things: First, remove the Array.Reverse(array);, you already start from the high side, so no need to reverse it.

Second:

            if (i == 0)
            {
                sum  = 1;
            }
            else
            {
                sum  = (int)Math.Pow(2, i);
            }

Here you check for i, but you actually have to check array[i] and you only need to increase your sum if there is a one, so change it to

            if (array[i] == '1')
            { 
                sum  = (int)Math.Pow(2, npower);
            }

Third:

Console.Write(" "   array[i] * (int)Math.Pow(2, npower1)   "");

array[i] is of type char, and it contains the ASCII values of 0 or 1, which is 48 and 49. So you actually multiply 48/49 with your Math.Pow result, that's why you have so high values. Change it to:

int.Parse( array[i].ToString() ) * (int)Math.Pow(2, npower1)

Another thing is validating your user input. You may want to check if the user only used 0 and 1 as input in the future.

You can test it here.

CodePudding user response:

Good morning Juan Charistheas Hawu on stackoverflow I don't know if stackoverflow is the right place to review your code, in my opinion you should use code review stack exchange. Here you have some usefull links:

https://stackoverflow.com/a/51400949/4510954

https://codereview.meta.stackexchange.com/q/5777

Anyway here you have working example, please look into it and try to figure out for loop which is responsible for right counting the factor an binary charr array index.

void MainProgram()
{
    string binaryValue = "10100";
    char[] binaryChars = binaryValue.ToCharArray();
    int result = 0;
    for (int i = binaryChars.Length-1, j = 0; i >= 0; i--, j  )
    {
        try
        {
            int binaryInt = (int)(binaryChars[j] - '0');
            result  = OneFactor(i, binaryInt);
            if(i != 0)
                Console.Write("   ");
        }
        catch (Exception)
        {
            throw new ArgumentException("Cannot parse binary value");
        }
    }
    Console.Write($" = {result}");
}

int OneFactor(int facorValue, int selected = 0)
{
    Console.Write($"({selected}*2)^{facorValue}");
    if (facorValue == 0 && selected == 0)
        return 0;
    return (int)Math.Pow((selected * 2), facorValue);
}
  • Related