Differenze tra le versioni di "Convertire un numero da rappresentazione binaria in decimale"

Da Gambas-it.org - Wikipedia.
Riga 11: Riga 11:
  
  
Per ottenere la conversione in Gambas potremo utilizzare questo codice: |[[#Note|1]]|
+
Per ottenere la conversione in Gambas potremo utilizzare questo codice:  
  '''Public''' Sub Button1_Click()   
+
  '''Public''' Sub Main()   
 
   
 
   
Dim a As String   
+
  Dim s As String   
Dim b, Intero, InteroFinale As Integer 
+
  Dim bb As Byte[]
Dim Esponente, crt As Integer
+
  Dim j As Byte
 +
  Dim l As Long
 
   
 
   
  a = InputBox("Immetti un numero in formato binario:")  
+
  s = InputBox("Immetti un numero in formato binario:")
 
+
   
  Esponente = 0  
+
   bb = Byte[].FromString(s).Reverse()
   
+
   
   For b = Len(a) To 1 Step -1  
+
   For j = 0 To bb.Max
    
+
     l += Val(Chr(bb[j])) * (2 ^ j)
     crt = Int(Val(Mid(a, b, 1))
+
  Next
    Intero = crt * 2 ^ Esponente 
+
   
    Esponente += 1 
+
   Print Il corrispondente valore decimale è: "; l
    InteroFinale = InteroFinale + Intero  
 
   
 
   Next 
 
 
 
  Print InteroFinale
 
 
   
 
   
 
  '''End'''
 
  '''End'''
 
 
 
=Note=
 
[1] Il presente algoritmo è stato suggerito dall'utente ''Picavbg'' del forum di Gambas-it.org.
 

Versione delle 15:44, 31 gen 2014

Per convertire un numero, espresso in formato a rappresentazione binaria, nella corrispondente rappresentazione decimale, bisogna moltiplicare le cifre del numero binario per le potenze decrescenti di 2, e successivamente sommare i risultati.

Convertiamo, per esempio il numero binario 10101010:

(1 * 27) + (0 * 26) + (1 * 25) + (0 * 24) + (1 * 23) + (0 * 22) + (1 * 21) + (0 * 20) =

= (1 * 128) + (0 * 64) + (1 * 32) + (0 * 16) + (1 * 8) + (0 * 4) + (1 * 2) + (0 * 1) =
 
= 128 + 0 + 32 + 0 + 8 + 0 + 2 =

=  170


Per ottenere la conversione in Gambas potremo utilizzare questo codice:

Public Sub Main()  

 Dim s As String  
 Dim bb As Byte[]
 Dim j As Byte
 Dim l As Long

  s = InputBox("Immetti un numero in formato binario:")

  bb = Byte[].FromString(s).Reverse()

  For j = 0 To bb.Max
    l += Val(Chr(bb[j])) * (2 ^ j)
  Next

  Print Il corrispondente valore decimale è: "; l

End