Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Binary to decimal using C#
To convert binary to decimal, here I have used a while loop and found the remainder of the Binary number, which is the input. After that, the remainder is multiplied by the base value and added.
This is what I did to get the decimal value −
while (val > 0) {
remainder = val % 10;
myDecimal = myDecimal + remainder* baseVal;
val = val / 10;
baseVal = baseVal * 2;
}
Example
Let us see the complete code to convert binary to decimal in C# −
using System;
using System.Collections.Generic;
using System.Text;
namespace Demo {
class toBinary {
static void Main(string[] args) {
int val = 1010, myBinary, remainder;
int myDecimal = 0, baseVal = 1;
myBinary = val;
while (val > 0) {
remainder = val % 10;
myDecimal = myDecimal + remainder * baseVal;
val = val / 10;
baseVal = baseVal * 2;
}
Console.Write("Binary Number : " + myBinary);
Console.Write("
Converted to Decimal: " + myDecimal);
Console.ReadLine();
}
}
}
Output
Binary Number : 1010 Converted to Decimal: 10
Advertisements