Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

โปรแกรม C# เพื่อแปลงไบนารีเป็นทศนิยม


ขั้นแรก ตั้งค่าไบนารี -

int num = 101;

ตอนนี้กำหนดไบนารีให้กับตัวแปรใหม่ -

binVal = num;

จนค่ามากกว่า 0 วนซ้ำเลขฐานสองและค่าฐานเช่นนี้

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

ตัวอย่าง

ต่อไปนี้คือโค้ดสำหรับแปลงไบนารีเป็นทศนิยม

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("\nDecimal: "+decVal);
         Console.ReadLine();
      }
   }
}

ผลลัพธ์

Binary Number: 101
Decimal: 5