Answers for "c# class to byte array"

C#
18

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);
Posted by: Guest on April-17-2020
1

c# class to byte array

// Convert an object to a byte array
private byte[] ObjectToByteArray(Object obj)
{
    if(obj == null)
        return null;

    BinaryFormatter bf = new BinaryFormatter();
    MemoryStream ms = new MemoryStream();
    bf.Serialize(ms, obj);

    return ms.ToArray();
}

// Convert a byte array to an Object
private Object ByteArrayToObject(byte[] arrBytes)
{
    MemoryStream memStream = new MemoryStream();
    BinaryFormatter binForm = new BinaryFormatter();
    memStream.Write(arrBytes, 0, arrBytes.Length);
    memStream.Seek(0, SeekOrigin.Begin);
    Object obj = (Object) binForm.Deserialize(memStream);

    return obj;
}
Posted by: Guest on March-20-2020
0

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;
}
Posted by: Guest on October-02-2020
0

c# class to byte array

private byte[] ObjectToByteArray(object obj)
{
  // proper way to serialize object
  var objToString = System.Text.Json.JsonSerializer.Serialize(obj);
  // convert that that to string with ascii you can chose what ever encoding want
  return System.Text.Encoding.ASCII.GetBytes(objToString);
}

private object ByteArrayToObject(byte[] bytes)
{
  // make sure you use same type what you use chose during conversation
  var stringObj = System.Text.Encoding.ASCII.GetString(bytes);
  // proper way to Deserialize object
  return System.Text.Json.JsonSerializer.Deserialize<object>(stringObj));
}
Posted by: Guest on July-20-2021

C# Answers by Framework

Browse Popular Code Answers by Language