Reputation: 2949
In C or C++, we can write the value of a variable directly onto a byte array.
int value = 3;
unsigned char array[100];
*(int*)(&array[10]) = value;
In C#, we also can do this by using unsafe
and fixed
keyword.
int value = 3;
byte[] array = new byte[100];
fixed(...) { ... }
However, Unity3D does not allow using unsafe
nor fixed
. In this case, what is the runtime cost-efficient way of doing it? I roughly guess it can be done with using a binary reader or writer class in .Net Core or .Net Framework, but I am not sure of it.
Upvotes: 1
Views: 283
Reputation: 378
You could also try to activate the unsafe keyword in Unity: How to use unsafe code Unity
That would spare you the effor to use any "hacks".
Upvotes: 2
Reputation: 101623
Since you can't use unsafe - you can just pack that int
value yourself:
int value = 3;
var array = new char[100];
array[10] = (char)value; // right half
array[11] = (char)(value >> 16); // left half
Because char
is basically ushort
in C# (16-bit number). This should do the same as you would in C++ with
*(int*)(&array[10]) = value;
Another approach is using `BitConverter:
var bytes = BitConverter.GetBytes(value);
array[10] = (char)BitConverter.ToInt16(bytes, 0);
array[11] = (char)BitConverter.ToInt16(bytes, 2);
But pay attention to endianess.
Upvotes: 2