B4J Question Parsing a Hex string?

agraham

Expert
Licensed User
Longtime User
My mind's gone a bit blank, so has anyone got a neat solution for parsing a hex (colour) value string like "FF8048020" to an Int? Bit.ParseInt("FF8048020", 16) throws a NumberFormatException, presumably because it thinks this is too large a positive number to be represented by an Int. I can think of various laborious ways of doing this but I feel that there must be a simple way that I am overlooking :(
 
Last edited:

Daestrum

Expert
Licensed User
Longtime User
Are you sure the hex is correct as it contains 9 characters?

As an int value it hits the max value for an int at 2147483647

Using big numbers it equates to 68585553952 which is too large for an int
 
Upvote 0

agraham

Expert
Licensed User
Longtime User
It's a typo :( It should be "FF804020" but that's just an example. Most Int colour values are negative because of the usual Alpha value of 255. Bit.Parse seems to always assume the the number to be parsed is positive and hence thinks these hex representations are too large to be represented by an Int.
 
Upvote 0

Daestrum

Expert
Licensed User
Longtime User
you might have to use BigNumbers to get the real positive value 4286595104, but again it wont fit in an int (2147483647), but displays correctly as a long.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
throws a NumberFormatException, presumably because it thinks this is too large a positive number to be represented by an Int.
That's true.

Not tested too much:
B4X:
Sub ParseHexColor (s As String) As Int
   s = s.Replace("#", "").Replace("0x", "")
   If s.length = 6 Then
       Return Bit.Or(0xff000000, Bit.ParseInt(s, 16))
   Else If s.Length = 8 Then
       Return Bit.Or(Bit.ShiftLeft(Bit.ParseInt(s.SubString2(0, 2), 16), 24), Bit.ParseInt(s.SubString(2), 16))
   End If
   Log("Invalid color: " & s)
   Return 0
End Sub

B4X:
Dim x As B4XView = MainForm.RootPane
x.Color = ParseHexColor("33FF0000")
 
Upvote 0
Top