【问题标题】:C# Byte[] to long reverse not workingC# Byte[] 到长反转不起作用
【发布时间】:2013-05-25 18:26:56
【问题描述】:

为什么这个程序不起作用?我将一个字节数组转换为长数组。然后从 long 我转换回字节数组。生成的字节数组与原始数组不同。

class Program
{
    static void Main(string[] args)
    {
        byte[] myBytes = { 0, 0, 0, 32, 56, 99, 87, 34, 56, 56, 34, 33, 67
                         , 56, 66, 72, 1, 0, 0, 56, 0, 22};

        long data = BitConverter.ToInt64(myBytes, 0);

        byte[] byteData = BitConverter.GetBytes(data);

        Console.WriteLine("byte array: " + BitConverter.ToString(myBytes));
        Console.WriteLine("byte array: " + BitConverter.ToString(byteData));
    }
}

【问题讨论】:

  • 作为方法名称(ToInt64) 意味着long 的长度为 64 位(8 字节)。
  • 它不是不工作,但没有像你预期的那样工作
  • 是的,你在那个数组中有 22 个字节,int64 是 8。你为什么要转换成 long 呢?

标签: c# bytearray long-integer bitconverter


【解决方案1】:

由于l4V 已经gave 是正确的假设,我只想将其添加为一个回答,但我认为我的答案不值得任何投票,因为所有赞成票都应该投给l4V。点赞他的评论。

来自BitConverter.ToInt64

ToInt64 方法将字节从索引 startIndex 转换为 startIndex + 7 转换为 Int64 值。

因此,基本上,此对话仅占用 byte 数组的 8 字节 (0, 0, 0, 32, 56, 99, 87, 34)。在这种情况下,您的数组的其他字节将被忽略。

【讨论】:

    【解决方案2】:

    字节长度超过long 可以容纳的(8 字节,64 位)。

    对于替代解决方案,如果您的目标框架高于(包括).Net 4.0,我建议使用BigInteger

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-13
      • 2014-12-24
      • 1970-01-01
      • 2012-01-02
      • 1970-01-01
      • 2016-04-30
      • 1970-01-01
      相关资源
      最近更新 更多