F#: Converting a string into an array of bytes
.net, byte, f#, string
Solution
Although you could write your own function to do the job, its best to stick with the built-in .NET methods:
String to bytes:
System.Text.Encoding.ASCII.GetBytes("hello world!")
Bytes to string:
System.Text.Encoding.ASCII.GetString([|104uy; 101uy; 108uy; 108uy;
111uy; 32uy; 119uy; 111uy; 114uy; 108uy; 100uy; 33uy|])
Problem
I'm writing a simple rc4 encryption/decryption utility as a first project. I'm stuck on trying to convert the given string into an array of bytes that can then be manipulated by the core algorithm. How do you convert a string into an array of bytes in functional 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 in C# it looks like: ``` 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(); } ```