# In C#, you can convert an integer to a binary value.

## Problem

What is the procedure for converting an integer number to its binary representation?

This is the code I’m using:

``````String input = "8";
String output = Convert.ToInt32(input, 2).ToString();
``````

However, there is one exception:

Asked by Thorin Oakenshield

## Solution #1

An integer is expressed as a string in your example. Let’s say your integer was actually an integer, and you want to take the integer and convert it to a binary string.

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

Which returns 1000.

Answered by Anthony Pegram

## Solution #2

In C#, you can convert from any classic base to any base.

``````string number = "100";
int fromBase = 16;
int toBase = 10;

string result = Convert.ToString(Convert.ToInt32(number, fromBase), toBase);

// result == "256"
``````

2, 8, 10, and 16 are supported bases.

Answered by sritmak

## Solution #3

Simple input, conversion, and output with no additional code.

``````using System;

namespace _01.Decimal_to_Binary
{
class DecimalToBinary
{
static void Main(string[] args)
{
Console.Write("Decimal: ");
int decimalNumber = int.Parse(Console.ReadLine());

int remainder;
string result = string.Empty;
while (decimalNumber > 0)
{
remainder = decimalNumber % 2;
decimalNumber /= 2;
result = remainder.ToString() + result;
}
Console.WriteLine("Binary:  {0}",result);
}
}
}
``````

Answered by Xenon

## Solution #4

http://zamirsblog.blogspot.com/2011/10/convert-decimal-to-binary-in-c.html

``````    public string DecimalToBinary(string data)
{
string result = string.Empty;
int rem = 0;
try
{
if (!IsNumeric(data))
error = "Invalid Value - This is not a numeric value";
else
{
int num = int.Parse(data);
while (num > 0)
{
rem = num % 2;
num = num / 2;
result = rem.ToString() + result;
}
}
}
catch (Exception ex)
{
error = ex.Message;
}
return result;
}
``````

Answered by Zamir

## Solution #5

primitive way:

``````public string ToBinary(int n)
{
if (n < 2) return n.ToString();

var divisor = n / 2;
var remainder = n % 2;

return ToBinary(divisor) + remainder;
}
``````

Answered by Daniel B

Post is based on https://stackoverflow.com/questions/2954962/convert-integer-to-binary-in-c-sharp