
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
Convert Decimal to Binary using C#
Let’s say we want to convert the number 48 to binary.
Firstly, set it and use the / and % operators and loop until the value is greater than 1 −
decVal = 48; while (decVal >= 1) { val = decVal / 2; a += (decVal % 2).ToString(); decVal = val; }
Now, display every bit of the binary as shown in the complete code −
Example
using System; using System.Collections.Generic; using System.Text; namespace Demo { class MyApplication { static void Main(string[] args) { int decVal; int val; string a = ""; decVal = 48; Console.WriteLine("Decimal = {0}", decVal); while (decVal >= 1) { val = decVal / 2; a += (decVal % 2).ToString(); decVal = val; } string binValue = ""; for (int i = a.Length - 1; i >= 0; i--) { binValue = binValue + a[i]; } Console.WriteLine("Binary = {0}", binValue); Console.Read(); } } }
Output
Decimal = 48 Binary = 110000
Advertisements