Can I create int.FromBytes(byte[] bytes) extension method in C#?
I need something with usage like this:
int a = int.FromBytes(new byte[]{1,2,3,4});
I'm using C# 7.3.
Actually I need this for ushort data type. For now I'm using extension method like this:
public static ushort FromBytes(sbyte msb, byte lsb)
{
ushort usmsb = (byte)msb;
ushort uslsb = lsb;
return (ushort)((usmsb << 8) + uslsb);
}
I'm using it like this:
ushort x = Helpers.FromBytes(1, 2);
I can't answer my closed question, so I post it here. This is how I did it and what I needed:
// two byte tuple extension
public static ushort ToUShort(this (byte msb, byte lsb) bytes)
{
ushort usmsb = bytes.msb;
ushort uslsb = bytes.lsb;
return (ushort)((usmsb << 8) + uslsb);
}
Usage:
byte byte1 = 32;
byte byte2 = 42;
ushort result = (byte1, byte2).ToUShort();
This is much better than extension for byte[] because you can't pass wrong number of bytes.