[英]How to convert a byte array to uint64 and back in C#?
我已经尝试了很久了。 我有一个字节数组,我想将其转换为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
类。
(如果您只需要在同一台机器上可逆,则我会坚持使用内置机器。)
我不确定您最初在进行左移和右移的目的是什么(我假设您正在尝试生成Uint64值来测试您的功能)。 要修复您的功能,只需将数字转换为UInt64
,然后对其进行测试。 或者,您可以使用后缀l
创建长文字。 例如UInt64[] responseBuffer = {0l,1l};
static void Main(string[] args)
{
int[] responseBuffer = { 0, 1, 2, 3, 4, 5 };
List<UInt64> bufferList = new List<ulong>();
foreach (var r in responseBuffer)
bufferList.Add((UInt64)r);
UInt64[] m_buffer = bufferList.ToArray();
foreach (var item in m_buffer)
Console.WriteLine(item);
//string m_s = "";
StringBuilder sb = new StringBuilder();
for (int k = 0; k < m_buffer.Length; 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());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.