gpt4 book ai didi

c# - 将 signed int 转换为两个 unsigned short 以进行重建

转载 作者:行者123 更新时间:2023-11-30 15:02:34 25 4
gpt4 key购买 nike

我目前正在使用 BitConverter 将两个未签名的 short 打包到一个已签名的 int 中。这段代码针对不同的值执行了数百万次,我认为代码可以进一步优化。这是我目前正在做的事情——您可以假设代码是 C#/NET。

// to two unsigned shorts from one signed int:
int xy = 343423;
byte[] bytes = BitConverter.GetBytes(xy);
ushort m_X = BitConverter.ToUInt16(bytes, 0);
ushort m_Y = BitConverter.ToUInt16(bytes, 2);

// convet two unsigned shorts to one signed int
byte[] xBytes = BitConverter.GetBytes(m_X);
byte[] yBytes = BitConverter.GetBytes(m_Y);
byte[] bytes = new byte[] {
xBytes[0],
xBytes[1],
yBytes[0],
yBytes[1],
};
return BitConverter.ToInt32(bytes, 0);

所以我想到,如果我进行位移,我可以避免构造数组的开销。但是对于我的一生,我无法弄清楚正确的轮类操作是什么。我第一次可悲的尝试涉及以下代码:

int xy = 343423;
const int mask = 0x00000000;
byte b1, b2, b3, b4;
b1 = (byte)((xy >> 24));
b2 = (byte)((xy >> 16));
b3 = (byte)((xy >> 8) & mask);
b4 = (byte)(xy & mask);
ushort m_X = (ushort)((xy << b4) | (xy << b3));
ushort m_Y = (ushort)((xy << b2) | (xy << b1));

有人可以帮助我吗?我在想我需要在移位之前屏蔽高字节和低字节。我看到的一些示例包括使用 type.MaxValue 或任意数字(例如负十二)进行减法,这非常令人困惑。

** 更新**

感谢您的精彩回答。以下是基准测试的结果:

// 34ms for bit shift with 10M operations
// 959ms for BitConverter with 10M operations

static void Main(string[] args)
{
Stopwatch stopWatch = new Stopwatch();

stopWatch.Start();
for (int i = 0; i < 10000000; i++)
{
ushort x = (ushort)i;
ushort y = (ushort)(i >> 16);
int result = (y << 16) | x;
}
stopWatch.Stop();
Console.WriteLine((int)stopWatch.Elapsed.TotalMilliseconds + "ms");

stopWatch.Start();
for (int i = 0; i < 10000000; i++)
{
byte[] bytes = BitConverter.GetBytes(i);
ushort x = BitConverter.ToUInt16(bytes, 0);
ushort y = BitConverter.ToUInt16(bytes, 2);

byte[] xBytes = BitConverter.GetBytes(x);
byte[] yBytes = BitConverter.GetBytes(y);
bytes = new byte[] {
xBytes[0],
xBytes[1],
yBytes[0],
yBytes[1],
};
int result = BitConverter.ToInt32(bytes, 0);
}
stopWatch.Stop();
Console.WriteLine((int)stopWatch.Elapsed.TotalMilliseconds + "ms");


Console.ReadKey();
}

最佳答案

最简单的方法是使用两类制:

int xy = -123456;
// Split...
ushort m_X = (ushort) xy;
ushort m_Y = (ushort)(xy>>16);
// Convert back...
int back = (m_Y << 16) | m_X;

ideone 上的演示:link .

关于c# - 将 signed int 转换为两个 unsigned short 以进行重建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12497383/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com