Byte Array to ArrayList Pattern

This design pattern shows how to copy byte arrays, and convert an array to an ArrayList object that can be more flexibly manipulated.

 

Pattern Syntax

 

 

// required for ArrayList class

using System.Collections;

 

private ScriptHelper helper = new ScriptHelper();

 

public void SendBytes()

{

   // prepare a byte array: the array size is fixed

   byte[] bytes = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05 };

 

   ProcessBytes( bytes );

}

 

private void ProcessBytes( byte[] bytes )

{

   // can't change the size of a byte array: can create a new larger array and copy the first one

   byte[] moreBytes = new byte[ bytes.Length + 3 ];

   bytes.CopyTo( moreBytes, 0 );

 

   // we can only fill the additional bytes we added

   moreBytes[ moreBytes.Length - 3 ] = 0x06;

   moreBytes[ moreBytes.Length - 2 ] = 0x07;

   moreBytes[ moreBytes.Length - 1 ] = 0x08;

 

   // display each byte value of the array

   for( int i = 0; i < moreBytes.Length; i++ )

   {

      helper.Logger.Debug( String.Format( "byte {0} = {1:X2}", i, moreBytes[i] ) );

   }

 

   // it's easier to convert the array to an ArrayList

   ArrayList list = new ArrayList( bytes );

 

   ProcessArrayList( list );

}

 

private void ProcessArrayList( ArrayList list )

{

   // now we can easily add as many extra bytes as we need

   list.Add( 0x06 );

   list.Add( 0x07 );

   list.Add( 0x08 );

   list.Add( 0x09 );

   list.Add( 0x0A );

 

   // display each item of the ArrayList

   for( int i = 0; i < list.Count; i++ )

   {

      helper.Logger.Debug( String.Format( "item {0} = {1:X2}", i, list[i] ) );

   }

}

 

 

Remarks

This design pattern:

 

See Also

Unidirectional Drivers

Design Patterns Index