1

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.

5
  • char array is not a byte array. Waht do you want to get? Commented Mar 23, 2018 at 5:57
  • You mean specifically how to write int in char array, or in general? Commented Mar 23, 2018 at 5:58
  • I changed the code. @Backs Commented Mar 23, 2018 at 6:03
  • @Evk Yes. I want to write int in the middle of char or byte array. Commented Mar 23, 2018 at 6:04
  • 1
    Unity supports unsafe and fixed keywords. See Djeurissen's answer Commented Mar 23, 2018 at 21:20

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.