2009-07-01 22 views
6

Voglio fare l'equivalente di questo:come convertire un tipo di valore in byte [] in C#?

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

sì, è un byte ora, ma considero voglio cambiare in futuro? come faccio a rendere byteArray contenuto? (Non mi interessa copiare).

risposta

11

La classe BitConverter potrebbe essere quello che stai cercando. Esempio:

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

Se il tuo enum era noto per essere un tipo Int32 derivata, si può semplicemente lanciare i suoi valori prima:

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

hanno ancora bisogno di lanciarlo, ma è meglio. Grazie! – Nefzen

+0

Se i tipi primitivi non sono sufficienti, vedere la mia risposta su come convertire qualsiasi tipo di valore. – OregonGhost

16

per convertire qualsiasi tipi di valore (non solo tipi primitivi) a matrici di byte e viceversa:

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

Molto bello, esattamente quello che stavo cercando, questa dovrebbe essere la risposta corretta in quanto BitConverter non funziona per tutti i tipi – Qwerty01

+0

BitConverter è * coerente * su tutti i tipi supportati su tutte le piattaforme in cui è però implementato. Va notato che i byte che si ottiene da questo metodo NON sono portabili su piattaforme diverse e potrebbero non funzionare anche su versioni diverse del framework .NET, quindi questo non è adatto per la serializzazione a meno che non si possa garantire il framework .NET. la versione è identica all'estremità di serializzazione e deserializzazione. Potrebbe rendere difficile l'aggiornamento dell'applicazione. –

+0

@MikeMarynowski: Ho appena visto il tuo commento. Non so cosa intendi. Questo codice NON implica la serializzazione binaria, utilizza il marshalling e il punto di marshalling è ottenere esattamente i byte che si richiede di chiamare P/Invoke o le API COM. Con questo metodo, ottieni esattamente i byte che hai definito nella tua struct (con StructLayoutAttribute e simili), indipendentemente dalla versione .NET o dalla piattaforma. – OregonGhost

1

Per chi è interessato a come funziona senza utilizzare BitConverter si può fare in questo modo:

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

In realtà è molto più semplice e sicuro usare BitConverter ma è divertente sapere!

0

È anche possibile eseguire una trasmissione semplice e trasmetterla al costruttore di array. Ha anche una lunghezza simile al metodo BitConverter.

new[] { (byte)mode } 
Problemi correlati