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

Convert binary to decimal using C#

PHPz
PHPzforward
2023-08-27 14:37:051175browse

使用 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;
}

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

Output

Binary Number : 1010
Converted to Decimal: 10

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete