How can I encode two numbers in a single Integer?

Mik*_*sen 4 .net javascript c# floating-point bitmask

I have the need to store a range of values (like 25-50 or 100-200), however to avoid a lot of database re-design and other work, I want to use a single Int32 to store both these numbers. I realize that I would only then have 16 bits for each number, but that's fine.

So, with two integer values this is pretty easy. I can do something like:

int mask = 50; //Right bits will have 50
mask |= (25 << 16); //Left bits will have 25

Console.WriteLine("Mask is: {0}", mask);
Console.WriteLine("Left is: {0}", (mask >> 16));
Console.WriteLine("Right is: {0}", (mask & 0xFFFF));
Run Code Online (Sandbox Code Playgroud)

Now, I have the right 16 bits storing the value 50, and the left 16 bits storing the value 25.

So what's the question?

Now, I want to use the same technique but I want to store two non-integers. For example, 1.5 and 1.75, or 2.00 and 2.25. .NET doesn't seem to support bit shift operators on float, single, double or decimal. Plus, I need to also read these values eventually in Javascript so it's doubtful whatever bit encoding floating points use would be completely compatible between platforms.

最好的方法是什么?我正在考虑的一种方法是使用整数,但将所有内容除以1000。这将使我在两个数字中都获得3个小数点精度,尽管我必须将整个内容long存储为大于65的任何值。不确定这是否是最好的方法。也许我很想念一些简单的事情。

nun*_*cal 5

只需一点数学就可以解决。

首先确定您的精度,例如2位数字,并且您的数字范围一直到1000

both = Math.Round(num1, 2) * 10000 + Math.Round(num2, 2);
Run Code Online (Sandbox Code Playgroud)

前4位是num1,然后是num2。

您可以让他们恢复该过程。

  • 假设您明天必须在其中一列中进行搜索,将很难维护。有时候,这种方法确实很有意义,例如将多个变量打包在一个变量中以节省传输字节。记录好黑客程序,因此下一个家伙不会傻眼。 (4认同)