Home > Backend Development > C#.Net Tutorial > Convert binary to decimal using C#

Convert binary to decimal using C#

PHPz
Release: 2023-08-27 14:37:05
forward
1172 people have browsed it

使用 C# 进行二进制转十进制

To convert binary to decimal, here I have used while loop and found the remainder of the binary number, which is the input. After that, multiply the remainders by the base value and add them.

This is how I got the decimal value -

while (val > 0) {
   remainder = val % 10;
   myDecimal = myDecimal + remainder* baseVal;
   val = val / 10;
   baseVal = baseVal * 2;
}
Copy after login

Example

Let’s see the complete code to convert binary to decimal in C#-

LiveDemo

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();
      }
   }
}
Copy after login

Output

Binary Number : 1010
Converted to Decimal: 10
Copy after login

The above is the detailed content of Convert binary to decimal using C#. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template