2009-07-01 89 views
6

我想要做的這相當於:如何在C#中將值類型轉換爲byte []?

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

是的,它現在是一個字節,但考慮到我想改變它的未來?如何讓byteArray包含內容? (我不在乎複製它)。

回答

11

BitConverter類可能是你在找什麼。例如:

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

如果枚舉被稱爲是一個Int32派生類型,你可以簡單地先投下自己的價值觀:

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

仍然需要施放它,但它更好。謝謝! – Nefzen 2009-07-01 11:21:59

+0

如果原始類型不夠,請參閱我的答案以瞭解如何轉換任何值類型。 – OregonGhost 2009-07-01 11:24:50

16

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

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

的人誰的興趣它是如何工作,而無需使用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更容易,更安全,但知道它很有趣!

0

你也可以做一個簡單的轉換,並將它傳遞給數組構造函數。它的長度也類似於BitConverter方法。

new[] { (byte)mode } 
相關問題