Home > Net >  How do I read 1 byte from STDIN?
How do I read 1 byte from STDIN?

Time:03-04

How do I read one byte from STDIN?

I tried searching for IO Word8 on Hoogle but there is nothing useful.

The closest I can find is System.IO.getChar, but it reads a Char not a Word8.

CodePudding user response:

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