DEV Community

Discussion on: Daily Challenge #158 - RGB To Hex Conversion

Collapse
 
craigmc08 profile image
Craig McIlwrath

Haskell, using the word8 type to ensure the inputs are from 0-255.

import Data.Bits
import Data.Word 

hexMap :: (Integral a) => a -> Char
hexMap = ("0123456789ABCDEF"!!) . fromIntegral

toHex :: Word8 -> String
toHex word = let lo = word .&. 15
                 hi = word .&. 240
             in  hexMap lo : hexMap (hi `shift` (-4)) : [] 

rgb :: Word8 -> Word8 -> Word8 -> String
rgb r g b = toHex r ++ toHex g ++ toHex b