简体   繁体   中英

C# Implicit/Explicit Byte Array Conversion

I have following problem. I want to convert an integer value or float value into an byte array. Normaly I use the BitConverter.GetBytes() method.

int i = 10;
float a = 34.5F;
byte[] arr;

arr = BitConverter.GetBytes(i);
arr = BitConverter.GetBytes(a);

Is there a possibility to do this with implicit/explicit methods??

arr = i;
arr = a;

and also the other way around??

i = arr;
a = arr;

You can do it through an intermediate class. The compiler won't do two implicit casts by itself, so you must do one explicit cast and then the compiler will figure out the second one.

The problem is that with implicit casts, you must either cast to or from the type you declare the cast in, and you cannot inherit from sealed classes like 'int'.

So, it is not elegant at all. Extension methods are probably more elegant.

If you declare the class below, you can then do things like:

        byte[] y = (Qwerty)3;
        int x = (Qwerty) y;

public class Qwerty
{
    private int _x;

    public static implicit operator byte[](Qwerty rhs)
    {
        return BitConverter.GetBytes(rhs._x);
    }

    public static implicit operator int(Qwerty rhs)
    {
        return rhs._x;
    }

    public static implicit operator Qwerty(byte[] rhs)
    {
        return new Qwerty {_x = BitConverter.ToInt32(rhs, 0)};
    }

    public static implicit operator Qwerty(int rhs)
    {
        return new Qwerty {_x = rhs};
    }
}

you could create extension methods to clean up the calling code a little bit - so you'd end up with:

 int i = 10;
 float a = 34.5F;
 byte[] arr;

 arr = i.ToByteArray();
 arr = a.ToByteArray();

The code for the extension methods would be something like:

public static class ExtensionMethods
    {
        public static byte[] ToByteArray(this int i)
        {
            return BitConverter.GetBytes(i);
        }

        public static byte[] ToByteArray(this float a)
        {
            return BitConverter.GetBytes(a);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM