]> gitweb.michael.orlitzky.com - hath.git/blob - src/Octet.hs
aaff3d2e0415a5029a13b5bb9fe957b449e26bd5
[hath.git] / src / Octet.hs
1 module Octet where
2
3 import Bit
4
5 -- An Octet consists of eight bits. For our purposes, the most
6 -- significant bit will come "first." That is, b1 is in the 2^7
7 -- place while b8 is in the 2^0 place.
8 data Octet = None | Octet { b1 :: Bit,
9 b2 :: Bit,
10 b3 :: Bit,
11 b4 :: Bit,
12 b5 :: Bit,
13 b6 :: Bit,
14 b7 :: Bit,
15 b8 :: Bit }
16 deriving (Eq, Show)
17
18 -- Convert each bit to its integer value, and multiply by the
19 -- appropriate power of two. Sum them up, and we should get an integer
20 -- between 0 and 255.
21 octet_to_int :: Octet -> Int
22 octet_to_int x =
23 128 * (bit_to_int (b1 x)) +
24 64 * (bit_to_int (b2 x)) +
25 32 * (bit_to_int (b3 x)) +
26 16 * (bit_to_int (b4 x)) +
27 8 * (bit_to_int (b5 x)) +
28 4 * (bit_to_int (b6 x)) +
29 2 * (bit_to_int (b7 x)) +
30 1 * (bit_to_int (b8 x))
31
32
33
34 octet_from_int :: Int -> Octet
35 octet_from_int x
36 | (x < 0) || (x > 255) = Octet.None
37 | otherwise = (Octet a1 a2 a3 a4 a5 a6 a7 a8)
38 where
39 a1 = if (x > 128) then One else Zero
40 a2 = if ((x `mod` 128) >= 64) then One else Zero
41 a3 = if ((x `mod` 64) >= 32) then One else Zero
42 a4 = if ((x `mod` 32) >= 16) then One else Zero
43 a5 = if ((x `mod` 16) >= 8) then One else Zero
44 a6 = if ((x `mod` 8) >= 4) then One else Zero
45 a7 = if ((x `mod` 4) >= 2) then One else Zero
46 a8 = if ((x `mod` 2) == 1) then One else Zero
47
48
49 octet_from_string :: String -> Octet
50 octet_from_string s =
51 case (reads s :: [(Int, String)]) of
52 [] -> Octet.None
53 x:_ -> octet_from_int (fst x)
54
55
56 -- The octet with the least possible value.
57 min_octet :: Octet
58 min_octet = Octet Zero Zero Zero Zero Zero Zero Zero Zero
59
60
61 -- The octet with the greatest possible value.
62 max_octet :: Octet
63 max_octet = Octet One One One One One One One One