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!
question from:
https://stackoverflow.com/questions/65902045/how-to-convert-int-to-byte-in-c-sharp-without-using-system-helper-functions 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…