Read Block Data using Csharp

The following example program illustrates how to parse block data using C#.

/// <summary>

/// Generates a IEEE block header for the specified size.

/// </summary>

/// <remarks>

/// The block header is of the form #[digit indicating number of digits to follow][length]

/// e.g. 201 bytes -> "#3201

///      9999 bytes -> "#49999"

///      0    bytes -> "#10"

/// </remarks>

/// <param name="size">Size of the block.</param>

/// <returns>Block header size string.</returns>

string GenerateBlockHeader(int size)

{

    string sz = size.ToString();

    return "#" + sz.Length.ToString() + sz;

}

/// <summary>

/// Parses a partially digested IEEE block length header, and returns

/// the specified byte length.

/// </summary>

/// <remarks>

/// The Stream pointer is assumed to point to the 2nd character of the block header

/// (the first digit of the actual length).  The caller is assumed to have parsed the

/// first two block header characters (#?, where ? is the number of digits to follow),

/// and converted the "number of digits to follow" into the int argument to this function.

/// </remarks>

/// <param name="numDigits">Number of digits to read from the stream that make up the

/// length in bytes.</param>

/// <returns>The length of the block.</returns>

int ReadLengthHeader(int numDigits)

{

    string bytes = string.Empty;

    for (int i = 0; i < numDigits; ++i)

          bytes = bytes + (char)Stream.ReadByte();

    return Convert.ToInt32(bytes);

}