char 中的镜像位,有限运算符 +,<<,&不允许循环,C 语言

发布于 2025-01-02 22:47:07 字数 271 浏览 6 评论 0 原文

准备考试的时候被这个问题卡住了: 允许的运算符为<<,+,&不允许循环最小临时变量。 用 C 编写一个函数,获取 4 位数字(字符)并返回镜像(相对于中心)位。 示例:给定 b4,b3,b2,b1 返回 b1,b2,b3,b4

O_o 谢谢!

可能不清楚,但允许使用通用语言工具('=='、if、>、< 等..)

Preparing for exam and got stuck at this question:
Allowed operators are <<,+,& no loops allowed and minimum temp variables.
Write a function in C, that gets 4-bit number (char) and returns mirrored (relative to center) bits.
Example: given b4,b3,b2,b1 return b1,b2,b3,b4

O_o thanks!

it might be not clear, but general language tools are allowed ('==',if,>,< etc..)

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

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

发布评论

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

评论(1

假装爱人 2025-01-09 22:47:07

考虑到只有运算符 <<、+、& 的约束并且除了 return 之外没有其他结构,这是不可能的。

要将 b3 从第三个位置移动到第二个位置,您需要一种向右移动的方法,这需要类似 >>或者 /。在提供的运算符中,没有一个可以与 b3 一起使用来设置第 2 或第 1 位位置。

如果你可以使用if语句和赋值运算符=,这是可能的。 那么您可以编写一个混乱的解决方案,例如更丑陋但更短的一行。

char flip(char c)
{
  char f;
  f = (c & 1) << 3 + (c & 2) << 1;
  if (c & 4)
    f = f + 2;
  if (c & 8)
    f = f + 1;
  return f;
}

如果您可以使用类似于 if ? 运算符,

char flip(char c)
{
  return (c & 1) << 3 + (c & 2) << 1 + ((c & 4) ? 2 : 0) + ((c & 8) ? 1 : 0);
}

This is not possible given the constraints of only the operators <<, +, & and no other constructs besides return.

To move b3 from the 3rd position to the 2nd position, you will need a way to shift to the right which requires something like >> or /. Of the operators provided, none can be used with b3 to set the 2nd or 1st bit position.

if you can use if statements and the assignment operator =, it is possible. You can then write a messy solution such as

char flip(char c)
{
  char f;
  f = (c & 1) << 3 + (c & 2) << 1;
  if (c & 4)
    f = f + 2;
  if (c & 8)
    f = f + 1;
  return f;
}

A more ugly but shorter one liner if you can use the similar to if ? operator.

char flip(char c)
{
  return (c & 1) << 3 + (c & 2) << 1 + ((c & 4) ? 2 : 0) + ((c & 8) ? 1 : 0);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文