Reputation: 151
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.
Upvotes: 1
Views: 114
Reputation: 32780
Have you taken a look at BitConverter
?
That said, generics is not a good fit for methods that take "primitive" types. There is no T: Primitive
or T: Numeric
constraint. The best you could do would be T: struct
but that is a pretty weak effort.
Also, generics means that there should be an infinite number of types valid for a given generic method, thats why its...well, generic. If your set of types is finite, and even more so if its just a handful, your are not using the right tool for the job.
So, to wrap it up, if you do know the types you need to support, the correct way to solve this is using method overloading, and BitConverter.GetBytes
does just that.
Upvotes: 2