How do I read 1 byte from STDIN?

Viewed 98
1 Answers

I think the easiest option is to use hGet from Data.ByteString like this:

import qualified Data.ByteString as B
import System.IO (stdin)
import Data.Word (Word8)

getByte :: IO Word8
getByte = B.head <$> B.hGet stdin 1

You can alternatively use hSetBinaryMode like this:

import System.IO
import Data.Word (Word8)

getByte :: IO Word8
getByte = do
  hSetBinaryMode stdin True
  c <- getChar
  hSetBinaryMode stdin False
  pure $! fromIntegral (fromEnum c)
Related