簡體   English   中英

如何在C#中將值類型轉換為byte []?

[英]how to convert a value type to byte[] in C#?

我想做的等效於:

byte[] byteArray;
enum commands : byte {one, two};
commands content = one;
byteArray = (byte*)&content;

是的,現在是一個字節,但是考慮到我將來要更改嗎? 如何使byteArray包含內容? (我不在乎復制它)。

要將任何值類型(不僅僅是原始類型)轉換為字節數組,反之亦然:

    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;
        }
    }

您正在尋找BitConverter類。 例:

int input = 123;
byte[] output = BitConverter.GetBytes(input);

如果已知您的枚舉是Int32派生類型,則可以簡單地首先強制轉換其值:

BitConverter.GetBytes((int)commands.one);

您可以使用BitConverter.GetBytes方法執行此操作。

對於不使用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;
}

實際上,使用BitConverter更加容易和安全,但是很有趣!

您也可以進行簡單的轉換並將其傳遞給數組構造函數。 它的長度也類似於BitConverter方法。

new[] { (byte)mode }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM