Android Question Hex2Rgb and Rgb2Hex?

Mashiane

Expert
Licensed User
Longtime User
Hi there

I'm using this code here, however its giving out different results. For example passing r=154, g=217 and b=234 to Rgb2eHex results with FF9AD9EA. Passing this hex back to Hex2Rgb results in r=249, g=173, b=158. Can someone please advise and help me what am I missing that these are not the same results?

rgb2hex : r=154, g=217 and b=234 > FF9AD9EA
hex2rgb : FF9AD9EA > r=249, g=173, b=158

Why, why, why?

B4X:
Sub Rgb2Hex(r As Int, g As Int, b As Int) As String
    Dim intC As Int
    Dim bc As ByteConverter
    intC = Colors.RGB(r,g,b)
    Return Bit.ToHexString(intC)
End Sub

Sub Hex2RGB(hex As String) As Map
    Dim m As Map
    m.Initialize
    Dim bc As ByteConverter
    Dim r,g,b As Int
    ' #E3E2E1
    'Log(hex.SubString2(1,3))
    r = Bit.ParseInt(hex.SubString2(1,3), 16)
    g = Bit.ParseInt(hex.SubString2(3,5), 16)
    b = Bit.ParseInt(hex.SubString2(5,7), 16)
    m.Put("r",r)
    m.put("g",g)
    m.Put("b", b)
    Return m
End Sub
 

Mashiane

Expert
Licensed User
Longtime User
You are passing the alpha channel
The code return a wrong value if you pass (#ff9ad9ea), but when you get the value in hex from rgb you get also the alpha channel.

So you should pass #9ad9ea, and it will works (for me works properly)
Thanks, its working now, I'm taking the last 6 numbers of the result and pre-pending # on them. Good result, you are a star!
 
Upvote 0

Similar Threads

Top