You can play the trick with IntPtr
and Marshal
to transform any structure (including byte
, ushort
and ulong
):
public static byte[] ToLEByteArray<T>(T value) where T: struct {
int size = Marshal.SizeOf(typeof(T));
byte[] bytes = new byte[size];
IntPtr p = Marshal.AllocHGlobal(size);
try {
Marshal.StructureToPtr(value, p, true);
Marshal.Copy(p, bytes, 0, size);
}
finally {
Marshal.FreeHGlobal(p);
}
if (!BitConverter.IsLittleEndian)
Array.Reverse(bytes);
return bytes;
}
....
Byte b = 123;
ushort s = 123;
ulong l = 123;
Byte[] result_byte = ToLEByteArray(b);
Byte[] result_ushort = ToLEByteArray(s);
Byte[] result_ulong = ToLEByteArray(l);
....
int i = 123456;
Byte[] result_int = ToLEByteArray(i);
EDIT : what's wrong with the implementation in question? (from the comment). Or, asking the question, what are these things with IntPtr
, Marshal
for?
ulong
:
public static byte[] UnsignedIntegerToLEByteArray(ulong value)
, ,
Byte x = 0x12;
ulong u = 0x0000000000000012;
-
new byte[] {0x12};
new byte[] {0x12, 0, 0, 0, 0, 0, 0, 0};
new byte[] {0x12, 0, 0, 0, 0, 0, 0, 0};
byte
ulong
. , , , (byte
, short
, ulong
..), , ..:
using (Stream stm = ...) {
...
Byte[] buffer = UnsignedIntegerToLEByteArray(...);
stm.Write(buffer, offset, buffer.Length);
...
}