Reputation: 51
To convert an int to a byte[], I would normally use BitConverter
, but I'm currently working within a framework called UdonSharp that restricts access to most System
methods, so I'm unable to use that helper function. This is what I have come up with so far:
private byte[] GetBytes(int target)
{
byte[] bytes = new byte[4];
bytes[0] = (byte)(target >> 24);
bytes[1] = (byte)(target >> 16);
bytes[2] = (byte)(target >> 8);
bytes[3] = (byte)target;
return bytes;
}
It works for the most part, but the problem is that it breaks when target
is greater than 255, throwing an exception Value was either too large or too small for an unsigned byte.
. I imagine this is because on the final part bytes[3] = (byte)target;
it is trying to convert a value greater than 255 directly to an int. But I just want it to convert the final 8 bits of the int to the final byte, not the whole thing. How can I accomplish that? Thanks in advance!
Upvotes: 4
Views: 186
Reputation: 1064044
It sounds like you're compiling in checked
mode; which is fine (albeit unusual), but sometimes you don't want that, so:
private byte[] GetBytes(int target)
{
byte[] bytes = new byte[4];
unchecked
{
bytes[0] = (byte)(target >> 24);
bytes[1] = (byte)(target >> 16);
bytes[2] = (byte)(target >> 8);
bytes[3] = (byte)target;
}
return bytes;
}
Also, note that allocating an array each time is really expensive; it is usually a better idea to pass in a buffer to write to.
Upvotes: 1
Reputation: 51
Thank you commenters! This did the trick:
private byte[] Int32ToBytes(int inputInt32)
{
byte[] bytes = new byte[4];
bytes[0] = (byte)((inputInt32 >> 24) % 256);
bytes[1] = (byte)((inputInt32 >> 16) % 256);
bytes[2] = (byte)((inputInt32 >> 8) % 256);
bytes[3] = (byte)(inputInt32 % 256);
return bytes;
}
Upvotes: 1