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
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.
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.
You are entirely missing the point. Colour values are Ints. They are generally negative. I don't want a positive number. I want to convert the hex representation of a colour to an Int value which Bit.ParseInt won't do.
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")
Thanks Erel. That confirms I wasn't missing something obvious. I thought that I was overlooking something simple and the best I could come up with was a bit like yours - also not fully tested yet!