Android Code Snippet Gerador de CPF (Brazilian document)

Douglas Farias

Expert
Licensed User
example of how to randomly generate valid CPF (Brazilian document).

B4X:
Sub Gerador_CPF(mascarado As Boolean) As String
   Private n1 As Int = Rnd(0,9)
   Private n2 As Int = Rnd(0,9)
   Private n3 As Int = Rnd(0,9)
   Private n4 As Int = Rnd(0,9)
   Private n5 As Int = Rnd(0,9)
   Private n6 As Int = Rnd(0,9)
   Private n7 As Int = Rnd(0,9)
   Private n8 As Int = Rnd(0,9)
   Private n9 As Int = Rnd(0,9)
   Private d1 As Int = n9*2+n8*3+n7*4+n6*5+n5*6+n4*7+n3*8+n2*9+n1*10
   Private d1 As Int = 11 - ( Round(d1 - (Floor(d1/11)*11)) )
   If ( d1 >= 10 ) Then d1 = 0
   Private d2 As Int = d1*2+n9*3+n8*4+n7*5+n6*6+n5*7+n4*8+n3*9+n2*10+n1*11
   d2 = 11 - ( Round(d2 - (Floor(d2/11)*11)) )
   If (d2>=10) Then d2 = 0
   If mascarado Then Return $"${n1}${n2}${n3}.${n4}${n5}${n6}.${n7}${n8}${n9}-${d1}${d2}"$ Else Return $"${n1}${n2}${n3}${n4}${n5}${n6}${n7}${n8}${n9}${d1}${d2}"$
End Sub
 

Claudio Oliveira

Active Member
Licensed User
Good one, @Douglas Farias. This is quite useful for testing purposes.
With some minor additions to your code, we get a random valid CNPJ generator, which turns out to be useful as well.

B4X:
Sub Gerador_CNPJ(mascarado As Boolean) As String
    Private n1 As Int = Rnd(0,9)
    Private n2 As Int = Rnd(0,9)
    Private n3 As Int = Rnd(0,9)
    Private n4 As Int = Rnd(0,9)
    Private n5 As Int = Rnd(0,9)
    Private n6 As Int = Rnd(0,9)
    Private n7 As Int = Rnd(0,9)
    Private n8 As Int = Rnd(0,9)
    Private n9 As Int = Rnd(0,9)
    Private n10 As Int = Rnd(0,9)
    Private n11 As Int = Rnd(0,9)
    Private n12 As Int = Rnd(0,9)
   
    Private d1 As Int = n1*5+n2*4+n3*3+n4*2+n5*9+n6*8+n7*7+n8*6+n9*5+n10*4+n11*3+n12*2
    d1 = 11 - (d1 Mod 11)
    If ( d1 >= 10 ) Then d1 = 0
   
    Private d2 As Int = n1*6 + n2*5 + n3*4 + n4*3 + n5*2 + n6*9 + n7*8 + n8*7 + n9*6 + n10*5 + n11*4 + n12*3 + d1*2
    d2 = 11 - (d2 Mod 11)
    If (d2>=10) Then d2 = 0
    If mascarado Then 
        Return $"${n1}${n2}.${n3}${n4}${n5}.${n6}${n7}${n8}/${n9}${n10}${n11}${n12}-${d1}${d2}"$ 
    Else 
        Return $"${n1}${n2}${n3}${n4}${n5}${n6}${n7}${n8}${n9}${n10}${n11}${n12}${d1}${d2}"$
    End If
End Sub
 
Top