C# program to convert binary to decimal

PHPz
Release: 2023-09-13 21:57:02
forward
1305 people have browsed it

将二进制转换为十进制的 C# 程序

First, set the binary value -

int num = 101;
Copy after login

Now assign the binary to a new variable -

binVal = num;
Copy after login

Loop over the binary number like this and the base value until the value is greater than 0,

while (num > 0) {
   rem = num % 10;
   decVal = decVal + rem * baseVal;
   num = num / 10;
   baseVal = baseVal * 2;
}
Copy after login

Example

The following is the code to convert binary to decimal.

Live Demo

using System;
using System.Collections.Generic;
using System.Text;
namespace Demo {
   class MyApplication {
      static void Main(string[] args) {
         int num, binVal, decVal = 0, baseVal = 1, rem;
         num = 101;
         binVal = num;
         while (num > 0) {
            rem = num % 10;
            decVal = decVal + rem * baseVal;
            num = num / 10 ;
            baseVal = baseVal * 2;
         }
         Console.Write("Binary Number: "+binVal);
         Console.Write("Decimal: "+decVal);
         Console.ReadLine();
      }
   }
}
Copy after login

Output

Binary Number: 101
Decimal: 5
Copy after login

The above is the detailed content of C# program to convert binary to decimal. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!