#18 Conversione da numero decimale a binario

Per convertire un numero intero in numero binario possiamo utilizzare la classe BitArray che converte un array di numeri in un array di bit. Per rappresentare la sequenza di bit, poi, utilizziamo una stringa e, per separare visivamente ogni byte, aggiungiamo anche uno spazio separatore:

Dim numero As Integer = 32767 
Dim numDecimale() As Integer = {numero} 
Dim numBinario As New BitArray(numDecimale) 
Dim str As String = "" 
Dim contaBit As Integer = 0 
For i As Integer = (numBinario.Count - 1) To 0 Step -1 
    If contaBit = 8 Then 
        str &= " " 
        contaBit = 0 
    End If 
    If numBinario.Item(i) = False Then 
        str &= "0" 
    Else 
        str &= "1" 
    End If 
    contaBit += 1 
Next 
MessageBox.Show(str)

Con il numero intero 32767 otteniamo la stringa seguente:

00000000 00000000 01111111 11111111

Posted on 7 febbraio 2008, in Articoli vari, Tips and tagged . Bookmark the permalink. 1 commento.

  1. molto interessante! Buona lettura!

Lascia un Commento

Fill in your details below or click an icon to log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Log Out / Modifica )

Foto Twitter

You are commenting using your Twitter account. Log Out / Modifica )

Foto di Facebook

You are commenting using your Facebook account. Log Out / Modifica )

Connecting to %s

Iscriviti

Get every new post delivered to your Inbox.

Join 211 other followers