如何在C#中将值类型转换为byte []?

Nef*_*zen 7 c# arrays

我想做相当于这个:

byte[] byteArray;
enum commands : byte {one, two};
commands content = one;
byteArray = (byte*)&content;
Run Code Online (Sandbox Code Playgroud)

是的,它现在是一个字节,但考虑我将来要改变它?如何让byteArray包含内容?(我不在乎复制它).

Ore*_*ost 18

将任何值类型(不仅仅是基本类型)转换为字节数组,反之亦然:

    public T FromByteArray<T>(byte[] rawValue)
    {
        GCHandle handle = GCHandle.Alloc(rawValue, GCHandleType.Pinned);
        T structure = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
        handle.Free();
        return structure;
    }

    public byte[] ToByteArray(object value, int maxLength)
    {
        int rawsize = Marshal.SizeOf(value);
        byte[] rawdata = new byte[rawsize];
        GCHandle handle =
            GCHandle.Alloc(rawdata,
            GCHandleType.Pinned);
        Marshal.StructureToPtr(value,
            handle.AddrOfPinnedObject(),
            false);
        handle.Free();
        if (maxLength < rawdata.Length) {
            byte[] temp = new byte[maxLength];
            Array.Copy(rawdata, temp, maxLength);
            return temp;
        } else {
            return rawdata;
        }
    }
Run Code Online (Sandbox Code Playgroud)

  • BitConverter 在所有实现它的平台上的所有支持类型上都是*一致的*。应该注意的是,从此方法返回的字节不能跨不同平台移植,甚至可能无法跨不同版本的 .NET 框架工作,因此这不适合序列化,除非您可以保证 .NET 框架版本在序列化和反序列化端是相同的。可能会使您的应用程序升级变得相当困难。 (2认同)

Jør*_*ode 13

BitConverter类可能是你在找什么.例:

int input = 123;
byte[] output = BitConverter.GetBytes(input);
Run Code Online (Sandbox Code Playgroud)

如果您的枚举被称为Int32派生类型,您可以先简单地转换它的值:

BitConverter.GetBytes((int)commands.one);
Run Code Online (Sandbox Code Playgroud)


Rob*_*ers 5

对于任何对它如何工作而不使用感兴趣的人BitConverter都可以这样做:

// Convert double to byte[]
public unsafe byte[] pack(double d) {
    byte[] packed = new byte[8]; // There are 8 bytes in a double
    void* ptr = &d; // Get a reference to the memory containing the double
    for (int i = 0; i < 8; i++) { // Each one of the 8 bytes needs to be added to the byte array
        packed[i] = (byte)(*(UInt64 *)ptr >> (8 * i)); // Bit shift so that each chunk of 8 bits (1 byte) is cast as a byte and added to array 
    }
    return packed;
}

// Convert byte[] to double
public unsafe double unpackDouble(byte[] data) {
    double unpacked = 0.0; // Prepare a chunk of memory ready for the double
    void* ptr = &unpacked; // Reference the double memory
    for (int i = 0; i < data.Length; i++) {
        *(UInt64 *)ptr |= ((UInt64)data[i] << (8 * i)); // Get the bits into the right place and OR into the double
    }
    return unpacked;
}
Run Code Online (Sandbox Code Playgroud)

事实上,它使用起来更容易、更安全,BitConverter但了解它很有趣!