Hex to Int?

Monkey Forums/Monkey Programming/Hex to Int?

siread(Posted 2011) [#1]
I'm trying to convert this function from Max...

Function SetHexColour(col:String)
	Local r:Int = Int("$"+col[0..2])
	Local g:Int = Int("$"+col[2..4])
	Local b:Int = Int("$"+col[4..6])
	SetColor(r, g, b)
End Function


Any ideas? At the moment it just sets colour to 0,0,0.


MonkeyPig(Posted 2011) [#2]
I use the following to convert hex strings to decimal...

	Function HexToDecimal:Int(token:String)
		Local val:Int = 0
		Local hex:String = token.ToUpper()
		For Local i:Int = 0 Until hex.Length()
			val *=16	
			If hex[i]>=48 And hex[i]<=57 Then
			
				val += (hex[i]-48)
			Else
				val += (hex[i]-55)
			Endif
			
		Next
		Return val
	End Function


So you'd need to change your code to something like...

Function SetHexColour(col:String)
	Local r:Int = HexToDecimal(col[0..2])
	Local g:Int = HexToDecimal(col[2..4])
	Local b:Int = HexToDecimal(col[4..6])
	SetColor(r, g, b)
End Function


Or just do the HexToDecimal once and extra the integers by masking & shifting.


siread(Posted 2011) [#3]
Great thanks. :)


siread(Posted 2011) [#4]
Anyone got a function for converting the other way, DecimalToHex?


Jesse(Posted 2011) [#5]
Function DecToHex:String(v:Int)
	Const hex:String = "0123456789ABCDEF"
	Local n:String
	For Local i = 0 Until 8
		n += String.FromChar(hex[(v Shr (28-(i*4))) & $F])
	Next
	Return n
End Function



siread(Posted 2011) [#6]
Beautiful, thanks. :D


AdamRedwoods(Posted 2011) [#7]
I know you're using strings, probably for things like user input, but here's the way without strings since strings can be kinda slow:

Function SetHexColour(hex:Int)
	Local r:Int = hex Shr 16 & $0000ff
	Local g:Int = hex Shr 8 & $0000ff
	Local b:Int = hex & $0000ff
	SetColor(r,g,b)
End