Skip to content

Instantly share code, notes, and snippets.

@ykon
Last active October 25, 2017 13:48
Show Gist options
  • Save ykon/69ba302e2fe004b960b752eab494a38b to your computer and use it in GitHub Desktop.
Save ykon/69ba302e2fe004b960b752eab494a38b to your computer and use it in GitHub Desktop.
Hex string in F#
(*
* Copyright (c) 2017 Yuki Ono
* Licensed under the MIT License.
*)
open System
open System.Text
let proceduralEncode (bytes:byte[]): string =
let sb = new StringBuilder(bytes.Length * 2)
for b in bytes do
sb.Append(b.ToString("x2")) |> ignore
sb.ToString()
let fpEncode (bytes:byte[]): string =
let byteToHex (b:byte) = b.ToString("x2")
Array.map byteToHex bytes |> String.concat ""
let proceduralDecode (hex:string): byte[] =
if hex.Length % 2 <> 0 then
invalidArg "hex" "hex.Length is not even"
let bytes = Array.create (hex.Length / 2) 0uy
let mutable i = 0
while i < bytes.Length do
bytes.[i] <- Convert.ToByte(hex.Substring(i * 2, 2), 16)
i <- i + 1
bytes
let fpDecode (hex:string): byte[] =
if hex.Length % 2 <> 0 then
invalidArg "hex" "hex.Length is not even"
let hexToByte (cs:char[]) = Convert.ToByte(new String(cs), 16)
Seq.chunkBySize 2 hex |> Seq.map hexToByte |> Seq.toArray
[<EntryPoint>]
let main argv =
let testBytes = [| 1uy; 2uy; 3uy; 4uy; 5uy; 11uy; 12uy; 13uy; 14uy; 15uy; 251uy; 252uy; 253uy; 254uy; 255uy |]
printfn "%s" (proceduralEncode testBytes)
printfn "%s" (fpEncode testBytes)
let testHex = "01020304050b0c0d0e0ffbfcfdfeff"
printfn "%s" (String.Join(",", (proceduralDecode testHex)))
printfn "%s" (String.Join(",", (fpDecode testHex)))
Console.Read() |> ignore
0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment