Биты хранятся в Vector

This commit is contained in:
2024-11-18 01:35:40 +03:00
parent abb078e1b6
commit e6d636cff2
4 changed files with 16 additions and 8 deletions

View File

@@ -9,6 +9,7 @@ module Lib
import Data.Char (ord, chr)
import Data.Bits (testBit)
import qualified Data.Vector.Unboxed as VU
createAlphabetFromText :: String -> [Char]
createAlphabetFromText [] = []
@@ -35,13 +36,15 @@ decryptCaesar alphabet shift =
where
alphabetLength = length alphabet
textToBits :: String -> [Int]
textToBits = concatMap charToBits
where charToBits c = [ if testBit (ord c) i then 1 else 0 | i <- [7,6..0] ]
textToBits :: String -> VU.Vector Int
textToBits text = VU.fromList $ concatMap charToBits text
where
charToBits c = [if testBit (ord c) i then 1 else 0 | i <- [7,6..0]]
bitsToText :: [Int] -> String
bitsToText [] = []
bitsToText bits = (chr $ bitsToInt (take 8 bits)) : bitsToText (drop 8 bits)
bitsToText :: VU.Vector Int -> String
bitsToText bits
| VU.null bits = []
| otherwise = (chr $ bitsToInt (VU.take 8 bits)) : bitsToText (VU.drop 8 bits)
where
bitsToInt charBits =
sum [bit * (2 ^ index) | (bit, index) <- zip charBits [7 :: Int, 6 .. 0]]
sum [bit * (2 ^ index) | (bit, index) <- zip (VU.toList charBits) [7 :: Int,6..0]]