c# - 如何在不使用系统帮助函数的情况下在 C# 中将 int 转换为 byte[]?

标签 c# type-conversion bit-shift

要将 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/

相关文章:

c# - 清理这个困惑的 bool 方法的更好方法

c# - Monitor.Pulse 和 Monitor.Wait 之间的竞争条件?

c# - 下载字符串超时

javascript - 将 javascript 集转换为字符串的最有效方法

javascript - 如何将字符串转换为数字?

c - 将 int 存储在 C 的 char 缓冲区中,然后检索相同的

c - 在 C 中将 uint8 拆分为 4 个单元 2,以便稍后获得单元 10

c# - 从 .msi 读取平台信息

c++ - vector的构造函数中的size_type是什么意思?

将 Pascal 的 "shr"转换为 C 的 ">>"