我已经尝试了很久了。我有一个字节数组,我想将其转换为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.ToUInt64
和BitConverter.GetBytes(ulong)
替代。
如果您希望能够指定字节序,则在我的MiscUtil库中有一个EndianBitConverter
类,可以使用。
(如果您只需要在同一台机器上可逆,则我会坚持使用内置机器。)
关于c# - 如何将字节数组转换为uint64并返回C#?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7532297/