[英]C# Pack 5 integers into 1
我正在尝试使用位移操作将5个整数(每个最多999个)打包和拆包为一个唯一的整数:
static UInt64 Combine(uint a, uint b, uint c, uint d, uint e)
{
return (a << 48) | (b << 32 ) | (c << 16) | (d << 8) | e;
}
但是,我无法将号码拆开。 谁能指导我做错了什么? 谢谢。
为了打包值0..999
,您需要10位,而不是8位。 十个将为您提供值0..1023
而八个将仅为您提供0..255
。
因此,您需要的功能类似于:
static UInt64 Combine(
uint a, uint b, uint c, uint d, uint e
) {
UInt64 retval = a;
retval = (retval << 10) | b;
retval = (retval << 10) | c;
retval = (retval << 10) | d;
retval = (retval << 10) | e;
return retval;
}
然后,要解压缩它们,只需提取每组十位,一次一次,例如:
static void Extract(UInt64 val, out uint a, out uint b,
out uint c, out uint d, out uint e
) {
e = Convert.ToUInt32(val & 0x3ff); val = val >> 10;
d = Convert.ToUInt32(val & 0x3ff); val = val >> 10;
c = Convert.ToUInt32(val & 0x3ff); val = val >> 10;
b = Convert.ToUInt32(val & 0x3ff); val = val >> 10;
a = Convert.ToUInt32(val & 0x3ff);
}
另一种存储数字的方式。 有点不同。 但是,我想我会把它呈现给您。 基本上,我们只是在模仿“联盟”:
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace Unions
{
public partial class Form1 : Form
{
[StructLayout(LayoutKind.Explicit)]
struct uShortArray
{
[FieldOffset(0)]
public ushort Bytes01;
[FieldOffset(2)]
public ushort Bytes23;
[FieldOffset(4)]
public ushort Bytes45;
[FieldOffset(6)]
public ushort Bytes67;
[FieldOffset(0)]
public long long1;
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, System.EventArgs e)
{
uShortArray ua = default(uShortArray);
ua.Bytes01 = 999;
ua.Bytes23 = 164;
ua.Bytes45 = 581;
ua.Bytes67 = 43;
MessageBox.Show($"ua = [Bytes 0 - 1 : {ua.Bytes01}] ... [Byte 2 - 3 : {ua.Bytes23}] ... [Bytes 4 - 5 : {ua.Bytes45}] ... [Bytes 6 - 7 : {ua.Bytes67}] ... [long1 : {ua.long1}]");
uShortArray ua2 = default(uShortArray);
Combine(out ua2, 543, 657, 23, 999);
MessageBox.Show($"ua2 = [Bytes 0 - 1 : {ua2.Bytes01}] ... [Byte 2 - 3 : {ua2.Bytes23}] ... [Bytes 4 - 5 : {ua2.Bytes45}] ... [Bytes 6 - 7 : {ua2.Bytes67}] ... [long1 : {ua2.long1}]");
uShortArray ua3 = default(uShortArray);
ua3.long1 = ua.long1; //As you can see, you don't need an extract. You just assign the "extract" value to long1.
MessageBox.Show($"ua3 = [Bytes 0 - 1 : {ua3.Bytes01}] ... [Byte 2 - 3 : {ua3.Bytes23}] ... [Bytes 4 - 5 : {ua3.Bytes45}] ... [Bytes 6 - 7 : {ua3.Bytes67}] ... [long1 : {ua3.long1}]");
}
private void Combine(out uShortArray inUA, ushort in1, ushort in2, ushort in3, ushort in4)
{
inUA = default(uShortArray);
inUA.Bytes01 = in1;
inUA.Bytes23 = in2;
inUA.Bytes45 = in3;
inUA.Bytes67 = in4;
}
}
}
该结构仅存储4个值。 但是,您可以使用更大的类型(而不是长型)来容纳更多数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.