2009-07-21 53 views
5

我正在寫一個簡單的rc4加密/解密實用程序作爲第一個項目。我堅持試圖將給定的字符串轉換爲可由核心算法操縱的字節數組。如何將字符串轉換爲函數f#中的字節數組?F#:將字符串轉換爲字節數組

//From another thread 
let private replace find (repl : string) (str : string) = str.Replace(find, repl) 

//let private algorithm bytes = blah blah blah 

let Encrypt (decrypted : string) = 
    decrypted.Chars 
    |> Array.map(fun c -> byte.Parse(c)) // This line is clearly not working 
    // |> algorithm 
    |> BitConverter.ToString 
    |> replace "-" "" 

FYI在C#中,它看起來像:

public static string Encrypt(string decrypted) 
    { 
     byte[] bytes = new byte[decrypted.Length]; 

     for (int i = 0; i < decrypted.Length; ++i) 
      bytes[i] = (byte)decrypted[i]; 

     Algorithm(ref bytes); 

     return BitConverter.ToString(bytes).Replace("-", "").ToLower(); 
    } 

回答

8

雖然你可以編寫自己的函數來完成這項工作,盡最大努力與內置的.NET方法堅持:

字符串字節:

System.Text.Encoding.ASCII.GetBytes("hello world!") 

字節串:

System.Text.Encoding.ASCII.GetString([|104uy; 101uy; 108uy; 108uy; 
      111uy; 32uy; 119uy; 111uy; 114uy; 108uy; 100uy; 33uy|]) 
+0

這是我所需要的第一個。 Text.Encoding.ASCII.GetBytes(解密) – telesphore4 2009-07-21 21:23:06

1

你可以每Gradbot的要求做的直接翻譯

let Encrypt(decrypted : string) = 
    let bytes = Array.init decrypted.Length (fun i -> byte decrypted.[i]) 
    Algorithm(ref bytes) 
    BitConverter.ToString(bytes).Replace("-", "").ToLower() 
+0

看到這個翻譯是有用的,但我試圖學習功能性的做事方式。我不想用C#「口音」編寫F#。 – telesphore4 2009-07-21 22:07:21

2

作爲,最終代碼如下所示:

1)我不喜歡的類型轉換爲字節

2)主算法功能看起來很不起作用

建設性的批評是受歡迎的。

Rc4.fs

#light 

open System 
open MiscUtils 
open StringUtils 

let private key = "Mykey"B 
let private byteMask = 0xff 
let private byteMax = byteMask 

let private algorithm (bytes : byte[]) = 
    let mutable j = 0 
    let mutable i = 0 
    let mutable s = [| for c in 0 .. byteMax -> (byte) c |] 

    for i in 0 .. byteMax do 
     j <- (j + (int) (s.[i] + key.[i % key.GetLength(0)])) &&& byteMask 
     Swap (&s.[i]) (&s.[j]) 

    i <- 0 
    j <- 0 
    for x in 0 .. bytes.Length - 1 do 
     i <- (i + 1) &&& byteMask 
     j <- (j + (int) s.[i]) &&& byteMask 
     Swap (&s.[i]) (&s.[j]) 
     let mutable t = (int)(s.[i] + s.[j]) &&& byteMask 
     bytes.[x] <- bytes.[x] ^^^ s.[t] 

    bytes 

let Encrypt (decrypted : string) = 
    Text.Encoding.ASCII.GetBytes decrypted 
    |> algorithm 
    |> BitConverter.ToString 
    |> ToLower 
    |> Replace "-" "" 

let Decrypt (encrypted : string) = 
    [| for i in 0 .. 2 .. encrypted.Length - 1 -> Convert.ToByte(encrypted.Substring(i, 2), 16) |] 
    |> algorithm 
    |> System.Text.Encoding.ASCII.GetString 

StringUtils.Fs

#light 

let Replace find (repl : string) (str : string) = str.Replace(find, repl) 
let ToLower (str : string) = str.ToLower() 

MiscUtils.fs

#light 

let Swap (left : 'a byref) (right : 'a byref) = 
    let temp = left 
    left <- right 
    right <- temp 
相關問題