我想要做的这相当于:如何在C#中将值类型转换为byte []?
byte[] byteArray;
enum commands : byte {one, two};
commands content = one;
byteArray = (byte*)&content;
是的,它现在是一个字节,但考虑到我想改变它的未来?如何让byteArray包含内容? (我不在乎复制它)。
我想要做的这相当于:如何在C#中将值类型转换为byte []?
byte[] byteArray;
enum commands : byte {one, two};
commands content = one;
byteArray = (byte*)&content;
是的,它现在是一个字节,但考虑到我想改变它的未来?如何让byteArray包含内容? (我不在乎复制它)。
该BitConverter类可能是你在找什么。例如:
int input = 123;
byte[] output = BitConverter.GetBytes(input);
如果枚举被称为是一个Int32派生类型,你可以简单地先投下自己的价值观:
BitConverter.GetBytes((int)commands.one);
您可以使用BitConverter.GetBytes方法来执行此操作。
要转换的任何值类型(而不仅仅是原始类型)以字节数组反之亦然:
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
,你可以做这样的:
// 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 }
仍然需要施放它,但它更好。谢谢! – Nefzen 2009-07-01 11:21:59
如果原始类型不够,请参阅我的答案以了解如何转换任何值类型。 – OregonGhost 2009-07-01 11:24:50