convert string byte array to byte array c# code example

Example 1: c# string to byte array

string author = "Mahesh Chand";  
// Convert a C# string to a byte array  
byte[] bytes = Encoding.ASCII.GetBytes(author);  

// Convert a byte array to a C# string. 
string str = Encoding.ASCII.GetString(bytes);

Example 2: c# number to byte array

public byte[] ConvertNumToByte(int Number)
{
  byte[] ByteArray = new byte[32];
  string BinString = Convert.ToString(Number, 2);
  char[] BinCharArray = BinString.ToCharArray();
  try
  {
    System.Array.Reverse(BinCharArray);
    if (BinCharArray != null && BinCharArray.Length > 0)
    {
      for (int index = 0; index < BinCharArray.Length; ++index)
      {
        ByteArray[index] = Convert.ToByte(Convert.ToString(BinCharArray[index]));
      }
    }
  }
  catch
  {
  }
  return ByteArray;
}