-1

I tried with this code in C# but could not get the desired output and i cudn't find where my mstaking in logic.

int rem,n,num=0; 
while(n>0)  
{ 
    rem=n%2;  
    num=(num*10)+rem;  
    n=n/2;  
}  
Console.WriteLine(num);  

But it doesn't give me the right output please tell me how can i accomplish it.
Output:
6 after conversion it sould be 110 but its 11

avirk
  • 3,050
  • 7
  • 38
  • 57
  • 3
    You don't mention anything about what the inputs are, as well as what the outputs are, as well as what you the intention of the algorithm is. You should elaborate on all of those things so that others can help provide you an answer. – casperOne May 06 '11 at 12:30
  • Like I tell my testers: Expected, Actual, Steps to Reproduce. You have only one of them and a developer will always require the three. – Paul Turner May 06 '11 at 12:32
  • @Redx i mean that i can accept answer in c++ too becase i work with it too. – avirk May 06 '11 at 12:33
  • @avrik: You have a problem with the logic .. – Akram Shahda May 06 '11 at 12:52

11 Answers11

8

You can use method Convert.ToString for that:

string binValue = Convert.ToString(number, 2);

If you nead a leading zeros you can use String PadLeft method:

binValue = binValue.PadLeft(10, '0');
3

Your error is that you're adding the digits to "num" in reverse order.

reavowed
  • 322
  • 1
  • 8
3

There's an answer here: Decimal to binary conversion in c #

Essentially:

int value = 8;
string binary = Convert.ToString(value, 2);

Will this solve your problem or do you need to understand why your code wasn't working?

Community
  • 1
  • 1
nycdan
  • 2,819
  • 2
  • 21
  • 33
0
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (radioButton1.Checked == true)
                prime_not();
            else
                binary();
        }



        private void binary()
        {
            label1.Text = Convert.ToString(Convert.ToInt64(textBox1.Text), 2);
        }

        private void prime_not()
        {
            if (Convert.ToInt16(textBox1.Text) % 2 == 0)
                label1.Text= "Not Prime";
            else
                label1.Text = "Prime";
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void label1_Click_1(object sender, EventArgs e)
        {

        }

    }
}
0

Convert Decimal to Binary

int len = 8;

public string DeicmalToBin(int value, int len) 
{
        try
        {
            return (len > 1 ? DeicmalToBin(value >> 1, len - 1) : null) + "01"[value & 1];
        }
        catch(Exception ex){
            Console.Write(ex.Message);
        }
        return "";
    }

For more details Decimal to binary conversion

0
 int num = Convert.ToInt32(textBox1.Text);
 int rem = 0;
 string res = "";

 do
 {
     rem = num % 2;
     num /= 2;
     res=rem.ToString()+res;               
 } while (num > 0);

 textBox1.Text=res;
  • Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation](https://meta.stackexchange.com/q/114762/349538) would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you’ve made. – CertainPerformance Apr 08 '19 at 01:22
  • 1
    Code-only answers are discouraged. Please click on [edit] and add some words summarising how your code addresses the question, or perhaps explain how your answer differs from the previous answer/answers. [From Review](https://stackoverflow.com/review/low-quality-posts/22686847) – Nick Apr 08 '19 at 01:48
0

n is never set and will therefore always be zero, meaning your while(n>0) loop will never be called.

NateTheGreat
  • 2,295
  • 13
  • 9
  • 1
    n is never set and therefore the program won't compile with 'Use of unassigned variable' error. ;) – Dmitry May 06 '11 at 12:34
  • Dmitry - I think you mean warning because it is assigned to the value of 0. – Security Hound May 06 '11 at 12:35
  • 1
    No, I meant 'error'. (Just tested with VS2010. Program doesn't compile.) Maybe there is some setting to treat it as a warning, but by default it's an error. – Dmitry May 06 '11 at 12:40
  • @Ramhound `int rem,n,num=0;` only sets num. rem and n remain unassigned. They do not default to 0. Only fields take default values, not local variables. – Buh Buh May 06 '11 at 13:30
0
From Decimal to Binary...


using System;

class Program{

   static void Main(string[] args){

      try{

     int i = (int)Convert.ToInt64(args[0]);
         Console.WriteLine("\n{0} converted to Binary is {1}\n",i,ToBinary(i));

      }catch(Exception e){

         Console.WriteLine("\n{0}\n",e.Message);

      }

   }//end Main


        public static string ToBinary(Int64 Decimal)
        {
            // Declare a few variables we're going to need
            Int64 BinaryHolder;
            char[] BinaryArray;
            string BinaryResult = "";

            while (Decimal > 0)
            {
                BinaryHolder = Decimal % 2;
                BinaryResult += BinaryHolder;
                Decimal = Decimal / 2;
            }

            // The algoritm gives us the binary number in reverse order (mirrored)
            // We store it in an array so that we can reverse it back to normal
            BinaryArray = BinaryResult.ToCharArray();
            Array.Reverse(BinaryArray);
            BinaryResult = new string(BinaryArray);

            return BinaryResult;
        }


}//end class Program



From Binary to Decimal...


using System;

class Program{

   static void Main(string[] args){

      try{

         int i = ToDecimal(args[0]);
         Console.WriteLine("\n{0} converted to Decimal is {1}",args[0],i);

      }catch(Exception e){

         Console.WriteLine("\n{0}\n",e.Message);

      }

   }//end Main


                public static int ToDecimal(string bin)
        {
                    long l = Convert.ToInt64(bin,2);
                    int i = (int)l;
                    return i;
        }


}//end class Program

Code snippet taken from this.

FIre Panda
  • 6,537
  • 2
  • 25
  • 38
0
string binary = "";
while (decimalNum != 0) {
    int nextDigit = decimalNum & 0x01;
    binary = nextDigit + binary;
    decimalNum = decimalNum >> 1;
}

Console.WriteLine(binary);
aroth
  • 54,026
  • 20
  • 135
  • 176
0
int n = 100;
for (int i = sizeof(n) * 8 - 1; i >= 0; --i) {
    n & (1 << i) ? printf("1") : printf("0");
}

And the result is:

00000000000000000000000001100100
Ilya Matveychikov
  • 3,936
  • 2
  • 27
  • 42
0
int number = value;
int rem = 0;
int round = 0;
int result = 0; 

while(number > 1)  
{ 
    rem = number % 2;  
    result = result + (rem * (round ^ 10));  
    number = number / 2;  

    round ++;
}    

result = result + (number * (round ^ 10));  



Console.WriteLine(result);  
Akram Shahda
  • 14,655
  • 4
  • 45
  • 65