Reputation: 1925
I am trying to write a little tool to hide text in PGM image files by overwriting the LSB in each byte in the input. I need help writing a function such as
writeBit :: Bool -> Word8 -> Word8
writeBit b w = ...
where the ouput is equal to w
with its LSB set to b
. Can anyone help me get started with this?
Thanks
Upvotes: 2
Views: 185
Reputation: 48591
I'll echo bmk by saying that Syd Kerckhove's answer is the correct one, but one very short option is
setLSB :: Integral n => Bool -> n -> n
setLSB b w = w - 1 + fromEnum b + fromEnum (even w)
Upvotes: 1
Reputation: 1568
Besides the right answer, that you should use the module Data.Bits
, you could also write the function yourself if you only want to set/unset the least significant bit of the input byte. Using your function signature:
setLSB :: Bool -> Word8 -> Word8
setLSB b w
| b && even w = w + 1
| not b && odd w = w - 1
| otherwise = w
Upvotes: 1
Reputation: 833
Have a look at setBit and clearBit
setBit :: a -> Int -> a
clearBit :: a -> Int -> a
Upvotes: 4