xxxxxxxxxx
int number;
byte[] bytes = BitConverter.GetBytes(number);
if (BitConverter.IsLittleEndian)
Array.Reverse(bytes);
xxxxxxxxxx
// 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;
}
xxxxxxxxxx
int num = 255; // Replace 255 with your desired integer
byte result = Convert.ToByte(num);
xxxxxxxxxx
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));
}