September 26, 2020, 10:11:31 pm

News:

Own IWBasic 2.x ? -----> Get your free upgrade to 3.x now.........


Hex to RGB

Started by Brian, January 18, 2020, 06:10:16 am

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

Brian

Hello,

Can anyone help with this? I need to return the RGB equivalent of a Hex number, ie, send something like 0xA09E5F and have it return the RGB string RGB(95,158,160)

Thanks a lot,

Brian

h3kt0r

January 18, 2020, 09:42:24 am #1 Last Edit: January 18, 2020, 11:06:46 am by h3kt0r Reason: modified the code sample
Hex color code is (#RRGGBB).
Here is a code sample to retrieve RGB values from HEX values for a given color :

Code Select
': Here is a code sample to retrieve RGB values from HEX values for a color.
': Portions of code from jos de jong.
':
window mywnd
int selcolor

:' Create the main window
OpenWindow mywnd, 50, 50, 320, 240, @NOAUTODRAW|@MINBOX|@SYSMENU, 0, "Test Window",&mywnd_handler
SetWindowColor mywnd, RGB(128, 128, 128)
CONTROL mywnd, @SYSBUTTON,"Color request",2,2,100,20, @TABSTOP,1

WaitUntil mywnd = 0
End

:'
:' Main loop
:'
Sub mywnd_handler(), int

Select @Message

Case @IdCloseWindow
CloseWindow mywnd

Case @IDCONTROL
Select @CONTROLID

Case 1
:' Erase the window
Rect mywnd, 0, 0, 320, 240, RGB(128, 128, 128), RGB(128, 128, 128)

INT b, g, r : STRING ref, hr, hg, hb

selcolor = COLORREQUEST(mywnd, RGB(0,0,0))
Move mywnd, 1, 30
BACKPEN mywnd, selcolor
b = int(selcolor/65536)  
g = int(selcolor%65536/256)  
r = int(selcolor-b*65536-g*256)
FRONTPEN mywnd, RGB((r + 99), (g + 99), (b + 99))
Print mywnd, "VALUE RETURNED : " + str$(selcolor)

Move mywnd, 1, 45  
ref = str$(r)+","+str$(g)+","+str$(b)
Print mywnd, "RGB : " + ref

Move mywnd, 1, 60
hr = hex$(r): hg = hex$(g): hb = hex$(b)  
if len(hr) = 1 then hr = "0" + hr  
if len(hg) = 1 then hg = "0" + hg  
if len(hb) = 1 then hb = "0" + hb
Print mywnd, "HEX : " + "0x" + hr + hg + hb

Move mywnd, 1, 75
Print mywnd, "RGB from HEX : " + str$(hVal(hr)) + str$(hVal(hg)) + str$(hVal(hb))

EndSelect

EndSelect
 
Return 0

EndSub
':
': this sub returns the value of the given hexadecimal character
': returns -1 if the value is not found
':
SUB hVal(hexstring:STRING), INT
'
'
STRING sign
INT n, p, rgbColor

rgbColor = 0
p = 0
FOR n = LEN(hexstring) TO 1 STEP -1
sign = MID$(hexstring,n,1)
v = INSTR("0123456789ABCDEF", sign)-1
IF v<0 THEN RETURN -1 :'an unsupported character in the string
rgbColor += v * 16^p
p++
NEXT n

RETURN rgbColor
ENDSUB

Brian

Thanks a lot - that does it for me with a bit of juggling

Brian

h3kt0r

January 18, 2020, 10:04:15 am #3 Last Edit: January 18, 2020, 11:07:34 am by h3kt0r
Warning : i've modified the code as the returned HEX value was wrong !

Now it returns the correct value.

/* Edit : Added
Code Select
SUB hVal(hexstring:STRING), INTNow the code sample is fully functional */