[VB6][C#][VB.Net] 進制轉換,2進制轉(10進制、8進制、16進制)

  • 53635
  • 0
  • VB6
  • 2008-12-01

摘要:[VB6][C#][VB.Net] 進制轉換,2進制轉(10進制、8進制、16進制)

進制轉換還算蠻常使用的,2進制要轉換成其他進制時,最好先轉成10進制,這是以前念計概時所學到的,以下就使用VB6來做範例說明,相信其他的語言轉換的思考邏輯也是八九不離十。

VB6:

Option Explicit

Private Sub Command1_Click(Index As Integer)
    Select Case Index
    Case Is = 0
        Text1(1).Text = Oct(Dec(Text1(0).Text)) 'Oct
        Text1(2).Text = Dec(Text1(0).Text) 'Dec
        Text1(3).Text = Hex(Dec(Text1(0).Text)) 'Hex
    End Select
End Sub

Private Function Dec(ByVal sVa As String)
    Dim intVal As Integer, intl As Integer, i As Integer
    intVal = 0
    intl = Len(sVa)
    For i = intl To 1 Step -1
        intVal = intVal + Val(Mid(sVa, Len(sVa) - i + 1, 1)) * 2 ^ (i - 1)
    Next i
    Dec = intVal
End Function

執行結果

 

範例下載:VB6進制轉換.rar

利用.Net Framework型別轉換就能達到進制轉換,不知道JAVA能不能直接這樣做,如果有人知道麻煩告知一下小弟

資料出處:http://msdn.microsoft.com/zh-tw/library/swz6z5ks.aspx

 C#:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;


namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            string myBrinary = textBox1.Text;
            int myNum = Convert.ToInt32(myBrinary, 2);//轉10進制
            textBox2.Text = Convert.ToString(myNum, 8);//轉8進制
            textBox3.Text = myNum.ToString();
            textBox4.Text =Convert.ToString(myNum, 16);//轉16進制
        }


    }

}

執行結果如下:

範例下載:C#2進制轉換8,10,16.rar

 VB.NET:

Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim myBrinary As String = TextBox1.Text
        Dim myNum As Integer = System.Convert.ToInt32(myBrinary, 2) '轉十進制
        TextBox2.Text = Convert.ToString(myNum, 8) '轉8進制
        TextBox3.Text = myNum.ToString()
        TextBox4.Text = Convert.ToString(myNum, 16) '轉16進制
    End Sub

End Class

執行畫面如下:

範例下載:VB.NET2進制轉換8,10,16.rar

 

若有謬誤,煩請告知,新手發帖請多包涵


Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET

Image result for microsoft+mvp+logo