I want to give int
or short
or Single
or Double
to the function. And I want an array to be return in reverse order.
Like
fun(2.0f)
will return[0x40, 0, 0, 0]
fun(0x01020304)
will return[1, 2, 3, 4]
fun( (short) 0x0102)
will return[1, 2]
I've tried Convert any object to a byte[]
But I could not achieve my goal. I will be very to learn if this function can be written as generic <T>
type.
public static byte[] fun(object obj)
{
if (obj == null)
return null;
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
bf.Serialize(ms, obj);
byte[] ar = ms.ToArray();
Array.Reverse(ar);
return ar;
}
}
After @InBetween 's answer my code is below and works fine.
public static byte[] Reverse(byte[] ar )
{
Array.Reverse(ar);
return ar;
}
Reverse(BitConverter.GetBytes(2.0f);// gives me [0x40, 0, 0, 0] in a single line.