【问题标题】:How to convert int to byte[] in C# without using System helper functions?如何在不使用系统辅助函数的情况下在 C# 中将 int 转换为 byte[]?
【发布时间】:2021-04-30 06:40:37
【问题描述】:

要将 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 位转换为最终字节,而不是全部。我怎样才能做到这一点?提前致谢!

【问题讨论】:

  • 您需要屏蔽掉不需要的位:bytes[3] = (byte)(target & 0xFF)
  • 如果问题是屏蔽问题,那么他必须屏蔽所有四个字节......然后我建议你尝试使用int.MaxValueint.MinValue来确定。
  • 是的,在类型转换之前,所有结果都应该是 % 256。 (或其他评论中提到的位掩码)
  • 旁注:实际上有一个很好的理由避免在这里使用BitConverter,即使它可用——或者至少谨慎对待它; BitConverter 是 CPU-endian,这意味着它不会总是在所有设备上产生相同的输出;然而,shift+m​​ask 方法是与字节序无关的,并且在任何地方都可以正常工作。在现代 .NET 中,有一个 BinaryPrimitives 类型在很大程度上取代了 BitConverter;它处理跨度,并具有特定于字节序的方法。

标签: c# type-conversion bit-shift


【解决方案1】:

感谢评论者!这成功了:

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

【讨论】:

  • 注意& 0xFF在语义上是相同的,更常用于掩蔽; faster 是您需要进行基准测试的东西(我个人认为& 的表现优于%,但我不会下注我的房子)。或者:只需使用unchecked
【解决方案2】:

听起来你是在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;
}

另外,请注意,每次分配一个数组真的很昂贵;传递 in 一个缓冲区来写入通常是一个更好的主意。

【讨论】:

    猜你喜欢
    • 2013-07-02
    • 2014-05-19
    • 2018-03-06
    • 1970-01-01
    • 1970-01-01
    • 2011-08-19
    • 2013-07-08
    • 2022-01-01
    • 1970-01-01
    相关资源
    最近更新 更多