如何处理 fitBits 中的 n=32

发布于 2025-01-10 23:45:15 字数 723 浏览 4 评论 0原文

从计算机系统:程序员的角度进行练习,这就是我想到的。不幸的是,这在 n=32 的情况下不起作用,如果 n=32 它根本不会移动 x,所以无论如何它都会返回 1。如果 x=0x80000000 这是一个问题,因为在这种情况下它应该返回 0

/* 
 * fitsBits - return 1 if x can be represented as an 
 *  n-bit, two's complement integer.
 *   1 <= n <= 32
 *   Examples: fitsBits(5,3) = 0, fitsBits(-4,3) = 1
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 15
 *   Rating: 2
 */
int fitsBits(int x, int n) {
  int diff = 32 +(~n + 1);//diff between n and 32
  return !(x ^ ((x << diff) >> diff)); //shifts x left by diff then right by diff leaving the num unchanged if it would fit as an n-bit 2s comp int then xor's with x so it will be !0 if x matches shifted x or !1 otherwise
}

working on an exercise from Computer Systems: A programmer's perspective and this is what i came up with. Unfortunatly this doesn't work in the case that n=32, if n=32 it doesn't shift x at all so it returns 1 regardless. This is a problem if x=0x80000000 because in this case it should return 0

/* 
 * fitsBits - return 1 if x can be represented as an 
 *  n-bit, two's complement integer.
 *   1 <= n <= 32
 *   Examples: fitsBits(5,3) = 0, fitsBits(-4,3) = 1
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 15
 *   Rating: 2
 */
int fitsBits(int x, int n) {
  int diff = 32 +(~n + 1);//diff between n and 32
  return !(x ^ ((x << diff) >> diff)); //shifts x left by diff then right by diff leaving the num unchanged if it would fit as an n-bit 2s comp int then xor's with x so it will be !0 if x matches shifted x or !1 otherwise
}

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文