如何解决如何在不使用系统帮助函数的情况下在 C# 中将 int 转换为 byte[]?
要将 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;
}
,
听起来您是在 checked
模式下编译;这是好的(虽然不寻常),但有时你不想要,所以:
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;
}
另外,请注意每次分配一个数组确实很昂贵;向传入一个要写入的缓冲区通常是一个更好的主意。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。