VB
.NET - Conversão Numérica : Binária, Decimal, Octal e
Hexadecimal
Neste artigo eu vou mostrar como fazer conversões numéricas usando a linguagem VB .NET.
Vamos realizar conversões numéricas entre os formatos: binário, decimal, hexadecimal e octal.
Recursos usados:
Abra o VB 2010 Express e crie um novo projeto do tipo Windows Forms Application com o nome ConversaoNumericas;
Inclua uma classe no projeto via menu Project -> Add Class com o nome ConversorNumerico e inclua o código abaixo nesta classe:
Public Class ConversorNumerico
' Converte o binario para long
Public Function BinaryToLong(ByVal valor_binario As String) As Long
' Remove qualquer &B se existir
valor_binario = valor_binario.Trim().ToUpper()
If valor_binario.StartsWith("&B") Then valor_binario = valor_binario.Substring(2)
' remove os espaços no caso de bytes separados por espaços
valor_binario = valor_binario.Replace(" ", "")
' preenche a esquerda com zeros
valor_binario = New String("0", 64 - valor_binario.Length) & valor_binario
' le os bits da esquerda para direita
Dim hex_resultado As String = ""
For nibble_num As Integer = 0 To 15
' Converte para string hexadecimal
Dim fator As Integer = 1
Dim nibble_value As Integer = 0
For bit As Integer = 3 To 0 Step -1
If valor_binario.Substring(nibble_num * 4 + bit, 1).Equals("1") Then
nibble_value += fator
End If
fator *= 2
Next bit
hex_resultado &= nibble_value.ToString("X")
Next nibble_num
' Converte o resultado string em um long
Return Long.Parse(hex_resultado, Globalization.NumberStyles.HexNumber)
End Function
Public Function LongToBinary(ByVal valor_long As Long, Optional ByVal bytes_separados As Boolean = True) As String
' Converte em hexa.
Dim hex_string As String = valor_long.ToString("X")
' preenche com zero a esquerdas com 16 characters.
hex_string = New String("0", 16 - hex_string.Length) & hex_string
' le os digitos hexadecimal um de cada vez da esquerda para direita
Dim resultado_string As String = ""
For digito_numero As Integer = 0 To 15
' Converte o digito hexadecimal para binario
Dim digito_valor As Integer = Integer.Parse(hex_string.Substring(digito_numero, 1), Globalization.NumberStyles.HexNumber)
' Converte o valor em bits
Dim fator As Integer = 8
Dim nibble_string As String = ""
For bit As Integer = 0 To 3
If digito_valor And fator Then
nibble_string &= "1"
Else
nibble_string &= "0"
End If
fator \= 2
Next bit
' inclui a string a esquerda do resultado
resultado_string &= nibble_string
Next digito_numero
' adiciona espacços entre os bytes se quiser
If bytes_separados Then
Dim tmp As String = ""
For i As Integer = 0 To resultado_string.Length - 8 Step 8
tmp &= resultado_string.Substring(i, 8) & " "
Next i
resultado_string = tmp.Substring(0, tmp.Length - 1)
End If
' Returna o resultado
Return "&B" & resultado_string
End Function
End Class
|
Nesta classe temos dois métodos que realizam a conversão de binário para decimal e vice-versa.
No formulário padrão fom1.vb do projeto inclua 4 controles Labels e 4 controles textBox conforme leiaute abaixo:
![]() |
Agora inclua o código abaixo neste formulário:
Public Class Form1
Dim conversor As New ConversorNumerico()
Private Sub ExibirValores(ByVal source As TextBox)
' não chamar recursiavmente
Static ignorar_eventos As Boolean = False
If ignorar_eventos Then Exit Sub
ignorar_eventos = True
' Pegar o valor
Dim txt As String
Dim value As Long
Try
Select Case source.Name
Case "txtDecimal"
value = Long.Parse(source.Text)
Case "txtHexadecimal"
txt = UCase(Trim(source.Text))
If txt.StartsWith("&H") Then txt = txt.Substring(2)
value = Long.Parse(txt, Globalization.NumberStyles.HexNumber)
Case "txtOctal"
txt = UCase(Trim(source.Text))
If Not txt.StartsWith("&O") Then txt = "&O" & txt
value = CLng(txt)
Case "txtBinary"
value = conversor.BinaryToLong(source.Text)
End Select
Catch ex As Exception
MessageBox.Show("Erro ao converter valor" & vbCrLf & ex.Message, "Erro : ", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End Try
' exibe o avlor em diferentes formatos
If source.Name <> "txtDecimal" Then
txtDecimal.Text = value.ToString()
End If
If source.Name <> "txtHexadecimal" Then
txtHexadecimal.Text = value.ToString("X")
End If
If source.Name <> "txtOctal" Then
txtOctal.Text = "&O" & Oct$(value)
End If
If source.Name <> "txtBinario" Then
txtBinario.Text = conversor.LongToBinary(value)
End If
ignorar_eventos = False
End Sub
Private Sub txtValor_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtDecimal.TextChanged, _
txtHexadecimal.TextChanged, txtOctal.TextChanged, txtBinario.TextChanged
ExibirValores(sender)
End Sub
End Class
|
Estamos usando o evento TextChanged dos controles TextBox de forma que à medida que o usuário digita o valor a rotina ExibirValores() é chamada e os valores são convertidos nos formatos tratados.
Executando o projeto teremos o seguinte resultado:
![]() |
Pegue o projeto completo
aqui:
ConversaoNumerica.zip
|
Veja os
Destaques e novidades do
SUPER CD VB 2013
(sempre atualizado) : clique e confira !
Quer migrar para o VB .NET ? Veja mais sistemas completos para a plataforma .NET no Super DVD .NET , confira... Quer aprender C# ?? Chegou o Super DVD C# 2013 com exclusivo material de suporte e vídeo aulas com curso básico sobre C#. |
Mas nem todos deram ouvidos ao evangelho; pois Isaías diz: Senhor, quem deu crédito à nossa mensagem?Rom 10:16
Rom 10:17
Logo a fé é pelo ouvir, e o ouvir pela palavra de Cristo.Referências:
Super DVD Vídeo Aulas - Vídeo Aula sobre VB .NET, ASP .NET e C#