Haskell程式:將字串值轉換為位元組值
在Haskell中,我們將使用`ord`、`B.pack`和`fromNum`函式將字串值轉換為位元組值。在第一個示例中,我們將使用`(stringToBytes = map ord)`函式;在第二個示例中,我們將呼叫`(stringToBytes = B.pack)`函式;在第三個示例中,我們將使用`(byteList = map fromEnum str)`函式。
演算法
步驟1 − 匯入`Data.Char`模組。
步驟2 − 使用`ord`函式定義`stringToBytes`函式,如下所示:
步驟3 − 程式執行將從`main`函式開始。`main()`函式控制整個程式的執行。它被編寫為`main = do`。
步驟4 − 定義名為“str”的變數,該變數將儲存要轉換為位元組的字串。
步驟5 − 函式呼叫後,將相應於字串值的最終位元組值列印到控制檯。
示例1
在這個示例中,使用`ord`函式將字串值轉換為位元組值。
import Data.Char (ord) stringToBytes :: String -> [Int] stringToBytes = map ord main :: IO () main = do let str = "hello" bytes = stringToBytes str print bytes
輸出
[1 of 1] Compiling Main ( main.hs, main.o ) Linking main ... [104,101,108,108,111]
示例2
在這個示例中,使用`B.pack`函式將字串值轉換為位元組值。
import qualified Data.ByteString.Char8 as B stringToBytes :: String -> B.ByteString stringToBytes = B.pack main :: IO () main = do let str = "hello" bytes = stringToBytes str B.putStrLn bytes
輸出
[1 of 1] Compiling Main ( main.hs, main.o ) Linking main ... hello
示例3
在這個示例中,使用`B.pack`函式將字串值轉換為位元組值。
import qualified Data.ByteString.Char8 as B main :: IO () main = do let str = "hello world" byteStr = B.pack str putStrLn $ "String: " ++ str putStrLn $ "ByteString: " ++ show byteStr
輸出
[1 of 1] Compiling Main ( main.hs, main.o ) Linking main ... String: hello world ByteString: "hello world"
示例4
在這個示例中,使用`B.pack`函式將字串值轉換為位元組值。
import qualified Data.ByteString.Char8 as B main :: IO () main = do let str = "hello world" byteStr = B.pack str byteList = B.unpack byteStr putStrLn $ "String: " ++ str putStrLn $ "ByteList: " ++ show byteList
輸出
[1 of 1] Compiling Main ( main.hs, main.o ) Linking main ... String: hello world ByteList: "hello world"
示例5
在這個示例中,使用`fromEnum`函式將字串值轉換為位元組值。
import Data.List (map) main :: IO () main = do let str = "hello world" byteList = map fromEnum str putStrLn $ "String: " ++ str putStrLn $ "ByteList: " ++ show byteList
輸出
[1 of 1] Compiling Main ( main.hs, main.o ) Linking main ... String: hello world ByteList: [104,101,108,108,111,32,119,111,114,108,100]
結論
在Haskell中,將字串值轉換為位元組值是將表示為字串的字元序列轉換為位元組序列的過程。在Haskell中,字串表示為字元序列,而位元組表示為0-255範圍內的數值序列,表示單個位元組的值。
廣告