Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I read 1 byte from STDIN?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 = head . B.unpack <$> 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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading