User Tools

Site Tools


codesnippets:octets

This is an old revision of the document!


Octets

module Main where
 
import qualified Data.Word as W
import qualified Data.Bits as Bts
import Data.Bits ((.|.))
import qualified Data.List as L
 
main :: IO ()
main = do
    print $ atDefault 0x00 (-1) myOctet
    print $ atDefault 0x00 0 myOctet
    print $ atDefault 0x00 1 myOctet
    print $ atDefault 0x00 2 myOctet
    print $ atDefault 0x00 3 myOctet
    print $ atDefault 0x00 4 myOctet
 
myOctet = toOctets (0xA4B3C2D1 :: W.Word32)
 
atDefault :: a -> Integer -> [a] -> a
atDefault aDef _ [] = aDef                        -- case: is empty anyway
atDefault _ 0  (a:_) = a                          -- case: index is 0 -> take it
atDefault aDef nIndex  (a:la) 
    | nIndex > 0 = atDefault aDef (nIndex - 1) la -- case: index is positive
    | otherwise  = aDef                           -- case: index is negative
 
class Octetable w where
    toOctets :: w -> [W.Word8]
 
instance Octetable W.Word32 where
    toOctets w32 = 
        [ fromIntegral (w32 `Bts.shiftR` 24)
        , fromIntegral (w32 `Bts.shiftR` 16)
        , fromIntegral (w32 `Bts.shiftR` 8)
        , fromIntegral w32
        ]
This website uses cookies. By using the website, you agree with storing cookies on your computer. Also you acknowledge that you have read and understand our Privacy Policy. If you do not agree leave the website.More information about cookies
You could leave a comment if you were logged in.
codesnippets/octets.1615962447.txt.gz · Last modified: (external edit)

Except where otherwise noted, content on this wiki is licensed under the following license: CC0 1.0 Universal
CC0 1.0 Universal Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki