8/18/09

Bytes to String Function

BytesToString returns a byte array as a formatted string.

02-05-10 This function has been replaced with a generic version - Generic Array to String Function.
//C#
using System.Text;

namespace ExpressionSoftware.System
{
    public static class Byte
    {
        public static string BytesToString(byte[] bs, string format)
        {
            var sb = new StringBuilder(bs.Length * 4);
            foreach (byte b in bs)
            {
                sb.AppendFormat(format, b);
            }
            return sb.ToString();
        }
    }
}

//F# v1.9.7.8
namespace ExpressionSoftware.System
open System.Text

module Byte =
  let BytesToString(bs:byte[], format:string) =
    let sb = new StringBuilder(bs.Length * 4)
    bs |> Array.iter(fun b -> sb.AppendFormat(format, b) |> ignore)
    sb.ToString()

#PowerShell
function bytesToString($bs, $format)
{
  $bs | %{$result += ($format -f $_)}
  $result
}

Examples
//C#
byte[] bs = { 102, 111, 111 };
Debug.WriteLine(Byte.BytesToString(bs, "{0}"));  //default format
102111111  //output

//F#
let bs = [|102uy; 111uy; 111uy|]
Byte.BytesToString(bs, "{0:d4}-")  //4 digit width format
|> (fun s -> printfn "%s" s)
0102-0111-0111-  //output

#PowerShell
[byte[]]$bs = 102,111,111
bytesToString $bs '{0:x} ' #hex format
66 6f 6f  #output

No comments:

Post a Comment