c# - 如何将字节数组转换为uint64并返回C#?

标签 c# bit-shift

我已经尝试了很久了。我有一个字节数组,我想将其转换为ulong并将值返回给另一个函数,并且该函数应将字节值取回。

我尝试了移位,但在少数情况下未成功。除了移位以外,还有其他选择吗?还是您有个简短的例子?谢谢您的帮助。

这是我使用的移位代码,我不明白为什么第二个条目不是00000001:

using System;
using System.Text;


namespace ConsoleApplication1
{
class Program
{
    static void Main(string[] args)
    {

         int[]responseBuffer = {0,1,2,3,4,5};


        UInt64 my = (UInt64)(((UInt64)(((responseBuffer[0]) << 40) & 0xFF0000000000)) |
              (UInt64)(((responseBuffer[1]) << 32) & 0x00FF00000000) |
              (UInt64)(((responseBuffer[2]) << 24) & 0x0000FF000000) |
              (UInt64)(((responseBuffer[3]) << 16) & 0x000000FF0000) |
               (UInt64)(((responseBuffer[4]) << 8) & 0x00000000FF00) | 
               (UInt64)(responseBuffer[5] & 0xFF));

         UInt64[] m_buffer = {(UInt64)((my >> 40) & 0xff),
                             (UInt64)((my >> 33) & 0xff) ,
                             (UInt64)((my >> 24) & 0xff) ,
                             (UInt64)((my>> 16) & 0xff) ,
                             (UInt64)((my>> 8) & 0xff) ,
                             (UInt64)(my& 0xff)};

         Console.WriteLine("" + m_buffer[1]);

            //string m_s = "";
            StringBuilder sb = new StringBuilder();
            for (int k = 0; k < 6; k++)
            {
                int value = (int)m_buffer[k];
                for (int i = 7; i >= 0; i--)
                {
                    if ((value >> i & 0x1) > 0)
                    {
                        sb.Append("1");
                        value &= (Byte)~(0x1 << i);
                    }
                    else
                        sb.Append("0");
                }
                sb.Append(" ");
            }   
                  Console.WriteLine(sb.ToString());
                  Console.Read();
    }
}


}

最佳答案

首先,我要弄清楚移位的问题,以防万一您再次需要它。它应该工作正常。

其次,如果您愿意使用系统字节序,则可以使用BitConverter.ToUInt64BitConverter.GetBytes(ulong)替代。

如果您希望能够指定字节序,则在我的MiscUtil库中有一个EndianBitConverter类,可以使用。

(如果您只需要在同一台机器上可逆,则我会坚持使用内置机器。)

关于c# - 如何将字节数组转换为uint64并返回C#?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7532297/

相关文章:

c# - 如何在 C# 中使用 Bogus 库生成字符串列表?

c# - SQL LINQ 选择标题和属于该标题的列表

java - 按位运算 Java - 长到二进制

c++ - C++ 中的按位数学运算

c# - 图像 split 成 9 block

c# - APPlitools:执行checkWindow()函数时显示401 unauthorized

javascript - 24 位无符号整数

c - c 中的分数移位

c++ - SSE 移位指令在后续指令中导致奇怪的输出 (-1.#IND00)?

c# - 我可以从 XML 文档生成 .MD 文件吗?