要将 int 转换为 byte[],我通常会使用 BitConverter
,但我目前正在一个名为 UdonSharp 的框架内工作,该框架限制对大多数 System
的访问。方法,所以我无法使用该辅助函数。这是我到目前为止想出的:
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;
}
它在大多数情况下都有效,但问题是它在 target
时会中断。大于 255,抛出异常 Value was either too large or too small for an unsigned byte.
.我想这是因为在最后一部分 bytes[3] = (byte)target;
它试图将大于 255 的值直接转换为 int。但我只是希望它将 int 的最后 8 位转换为最后一个字节,而不是全部。我怎样才能做到这一点?提前致谢!
最佳答案
谢谢评论者!这做到了:
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;
}
关于c# - 如何在不使用系统帮助函数的情况下在 C# 中将 int 转换为 byte[]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65902045/