如何在 C# 中将值类型转换为 byte[]?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1068541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to convert a value type to byte[] in C#?
提问by Nefzen
I want to do the equivalent of this:
我想做相当于:
byte[] byteArray;
enum commands : byte {one, two};
commands content = one;
byteArray = (byte*)&content;
yes, it's a byte now, but consider I want to change it in the future? how do I make byteArray contain content? (I don't care to copy it).
是的,它现在是一个字节,但考虑到我将来想改变它吗?如何让 byteArray 包含内容?(我不想复制它)。
采纳答案by J?rn Schou-Rode
The BitConverterclass might be what you are looking for. Example:
该BitConverter类可能是你在找什么。例子:
int input = 123;
byte[] output = BitConverter.GetBytes(input);
If your enum was known to be an Int32 derived type, you could simply cast its values first:
如果您的枚举已知是 Int32 派生类型,您可以先简单地转换其值:
BitConverter.GetBytes((int)commands.one);
回答by Sean
You can use the BitConverter.GetBytesmethod to do this.
您可以使用BitConverter.GetBytes方法来执行此操作。
回答by OregonGhost
To convert any value types (not just primitive types) to byte arrays and vice versa:
将任何值类型(不仅仅是原始类型)转换为字节数组,反之亦然:
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;
}
}
回答by Rob Sanders
For anyone who's interested in how it works without using BitConverter
you can do it like this:
对于任何对不使用它的工作原理感兴趣的人,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;
}
In reality it's much easier and safer to use BitConverter
but it's fun to know!
实际上,它使用起来更容易、更安全,BitConverter
但知道它很有趣!
回答by Erik Berkun-Drevnig
You can also just do a simple cast and pass it into the array constructor. It also similar in length to the BitConverter
method.
你也可以做一个简单的转换并将它传递给数组构造函数。它的长度也与BitConverter
方法相似。
new[] { (byte)mode }