B4J Code Snippet Random Hexcolor Generator

Ola...

I needed something like this... here we go...

B4X:
'generate a random hex color
Sub RandomHexColor As String
    Dim shex As StringBuilder
    shex.initialize
    shex.append("#")
   
    Dim hexValues As List
    hexValues.Initialize
    hexValues.AddAll(Array(0, 1 , 2 , 3 ,4 ,5 , 6 , 7 , 8 , 9, "A", "B", "C", "D", "E", "F"))
    '
    Dim i As Int
    For i = 0 To 5
        Dim idx As Int = Rnd(0, hexValues.Size)
        Dim hvalue As String = hexValues.Get(idx)
        shex.Append(hvalue)
    Next
    Return shex.tostring
End Sub

Update: Oops, fixed Rnd 2nd parameter to be (exclusive)
 
Last edited:

emexes

Expert
Licensed User
here we go...

In case the price of random numbers goes up:

B4X:
Sub RandomHexColor As String
    Return "#" & Bit.ToHexString(Rnd(0, 0x1000000)).ToUpperCase
End Sub

and if you really, really, really need six digits always, then perhaps the slightly kludgy:

B4X:
Sub RandomHexColor As String
    Return "#" & Bit.ToHexString(Rnd(0x1000000, 0x2000000)).SubString(1).ToUpperCase    'always generate 7 digits, then throw away the first one (pun intended)
End Sub
 
Last edited:

kimstudio

Active Member
Licensed User
Longtime User
Rnd(min, max) min inclusive and max exclusive, so I assume what emexes means is that it should be

B4X:
Dim idx As Int = Rnd(0, hexValues.Size)
 

Mashiane

Expert
Licensed User
Longtime User
This is one part of b4x that I really was not aware of, that 2nd variable being exclusive or will be 1 less. :oops:

Fortunately I dont use Rnd often on my code so its not a train smash.

Kinda embarrassing though... ?
 

Attachments

  • 1666086107403.png
    1666086107403.png
    9.7 KB · Views: 173

kimstudio

Active Member
Licensed User
Longtime User
Only because I code algorithms sometimes then I know Rnd and I know almost nothing about your expertise web stuff.. so please no embarrassing at all :)
 
Top