Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
724 views
in Technique[技术] by (71.8m points)

type conversion - How to convert int to byte[] in C# without using System helper functions?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...