[硬件问题的一部分]假设2的补码,32位字长。仅允许使用带符号的int和0到0xFF的常量。我被要求仅使用运算符将​​“ n”位(0 ! 〜&^ | + >我认为我可以存储并清除符号位,执行移位操作,并将存储的符号位替换到新位置。我想实现操作“ 31-n”(不使用“-”运算符来查找)以找到存储符号位后移位的适当位置。如果n为正,我可以使用表达式:“ 31 +(〜n + 1)”,但是我不认为这在n = 0的情况下会起作用。这是我到目前为止的内容:int logicalShift(int x, int n) {/* Store & clear sign bit, perform shift, and replace stored sign bit in new location */int bit = (x >> 31) & 1; // Store most significant bitx &= ~(1 << 31); // Clear most significant bitx = x >> n; // Shift by nx &= ~((~bit) << (31 - n)); // Replace MSbit in new locationreturn x;}任何帮助和/或提示表示赞赏。 (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 [编辑:已解决]感谢大家的帮助。 〜n + 1在这种情况下可以使n取反,包括对于n = 0(根据需要返回0)的情况。下面是功能代码(绝不是最优雅的解决方案)。公用事业运营是从以下机构借来的:How do you set, clear, and toggle a single bit?int logicalShift(int x, int n) {/* Store & clear sign bit, perform shift, and replace stored sign bit in new location */int bit = (x >> 31) & 1; // Store most significant bitx &= ~(1 << 31); // Clear most significant bitx = x >> n; // Shift by nx ^= ((~bit + 1) ^ x) & (1 << (31 + (~n + 1))); // Replace MSbit in new locationreturn x;} (adsbygoogle = window.adsbygoogle || []).push({});
10-07 13:01
查看更多