Home
F#
byte Array Examples
This page was last reviewed on Dec 22, 2023.
Dot Net Perls
Byte array. Many files can be most effectively processed as byte arrays—in F#, we can read byte arrays and create them. The language even has special support for byte arrays.
Array
With the B suffix, on a string literal, we can create a byte array. This is the easiest way to initialize a small byte array for use in an F# program.
Example. This program uses byte arrays in a variety of ways. Because it use a type from the System.IO namespace, it has an "open System.IO" directive at the top.
Part 1 We get a byte array from the disk by calling File.ReadAllBytes. The path will need to be adjusted to point to an existing file.
File
Part 2 We create a byte array literal. This syntax uses the uppercase "B" at the end of a string literal.
Part 3 We can create a byte array with byte literals with the array initialization syntax.
Part 4 If desired, we can separate each element with a newline instead of a semicolon. The indentation must be correct for this to work.
Part 5 We loop over the elements in a byte array with a for-in loop, printing them as we go along.
for
Part 6 With Array.map, we add 10 to each element of the array. Then we use Seq.iter to print each value in the new array.
Seq
open System.IO // Part 1: read in file from disk as byte array. let data = File.ReadAllBytes(@"/Users/sam/programs/output.webp") printfn $"Data length = {data.Length}" // Part 2: create a byte array with string syntax. let data2: byte[] = "cute dog"B printfn $"Data2 length = {data2.Length}" // Part 3: create a byte array with integer syntax. let data3 = [|100; 101; 102; 103|] printfn $"Data3 length = {data3.Length}" // Part 4: use separate lines for each value (indentation is important). let data4 = [|100 101 102 103|] printfn $"Data4 length = {data4.Length}" // Part 5: loop over elements in byte array. for b in data4 do printfn $"Byte in data4 = {b}" // Part 6: add to each element in byte array and print it out with Seq.iter. let result = Array.map (fun x -> x + 10) data4 result |> Seq.iter (fun x -> printfn $"Byte in result = {x}")
Data length = 4796 Data2 length = 8 Data3 length = 4 Data4 length = 4 Byte in data4 = 100 Byte in data4 = 101 Byte in data4 = 102 Byte in data4 = 103 Byte in result = 110 Byte in result = 111 Byte in result = 112 Byte in result = 113
Summary. Byte arrays can be used throughout F# programs in the same way as other arrays. Functions like Array.map can be used with byte arrays.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 22, 2023 (new).
Home
Changes
© 2007-2024 Sam Allen.