使用 16 位对 32 位值实现位移位

发布于 2024-10-08 02:15:08 字数 568 浏览 0 评论 0原文

我正在使用一种只能对 16 位数字进行二进制数学运算的语言,但我需要对 32 位值使用二进制数学运算,因此我必须编写一些自己的函数。例如,我将二进制 OR 实现为:

 _32bit_or(a,b){
  var{
   a1=round(a/(2**16));
   a2=a%(2**16);
   b1=round(b/(2**16));
   b2=b%(2**16);
  }
  .=((a1|b1) * (2**16)) + (a2|b2);
 }

将 32 位值拆分为两个 16 位部分,对每个部分进行 OR 操作,然后重新组合。够简单的。

但我现在需要实现移位,这并不那么容易,因为通过将数字分开、移位,然后重新组合,我会丢失位!我尝试的是:

 _32bit_rshift(a,b){
  var{
   a1=round(a/(2**16));
   a2=a%(2**16);
  }
  . = ((a1>>b) * (2**16)) + (a2>>b)
 }

但这当然行不通,正如我提到的那样。任何人都可以提供一些意见吗?

I'm working in a language that can only do binary math on 16-bit numbers but I need to use binary math on 32-bit values so I have to make some of my own functions. For example, I implemented binary OR as:

 _32bit_or(a,b){
  var{
   a1=round(a/(2**16));
   a2=a%(2**16);
   b1=round(b/(2**16));
   b2=b%(2**16);
  }
  .=((a1|b1) * (2**16)) + (a2|b2);
 }

Split the 32-bit value into two 16-bit portions, OR each portion, and recombine. Simple enough.

But I now need to implement shifting which isn't as easy because by breaking the numbers apart, shifting, and then recombining, I'm losing bits! What I tried was:

 _32bit_rshift(a,b){
  var{
   a1=round(a/(2**16));
   a2=a%(2**16);
  }
  . = ((a1>>b) * (2**16)) + (a2>>b)
 }

But this of course doesn't work as I mentioned. Can anyone provide some input?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

临走之时 2024-10-15 02:15:08

对于左移 1,先移位高位字,然后将低位字与 0x8000 进行“与”,如果“与”的结果不为 0,则将高位字与 1 进行“或”,然后移位低位字。

对于右移 1,先移位低位字,然后将高位字与 1 进行“与”,如果“与”的结果不为 0,则将低位结果与 0x8000 进行“或”,然后移位高位字。

移位超过一位需要更大的值来进行“与”运算,并在“或”运算之前进行适当的移位。

For a left shift 1, shift the upper word, AND the lower word with 0x8000 and OR the upper result with 1 if the result of the AND is not 0, then shift the lower word.

For a right shift 1, shift the lower word, AND the upper word with 1 and OR the lower result with 0x8000 if the result of the AND is not 0, then shift the upper word.

Shifting by more than one bit requires larger values to AND with and appropriate shifting before ORing.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文