K&放大器;与位运算 - [R运动混乱 [英] k&r exercise confusion with bit-operations

查看:120
本文介绍了K&放大器;与位运算 - [R运动混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的运动是:
写的函数setbits(X,P,N,Y),该返回x与开始在位置p设定为y的最右边的n位的n位,而使其他位不变。

The exercise is: Write a function setbits(x,p,n,y) that returns x with the n bits that begin at position p set to the rightmost n bits of y, leaving the other bits unchanged.

我在一个解决方案的尝试是:

My attempt at a solution is:

#include <stdio.h>

unsigned setbits(unsigned, int, int, unsigned);

int main(void)
{
    printf("%u\n", setbits(256, 4, 2, 255));
    return 0;
}

unsigned setbits(unsigned x, int p, int n, unsigned y)
{
    return (x >> (p + 1 - n)) | (1 << (n & y));
}

这可能不正确,但我在这里在正确的道路上?如果不是这样,我在做什么错了?我不能确定,为什么我不完全理解这一点,但我花了大约一个小时试图想出这个。

It's probably incorrect, but am I on the right path here? If not, what am I doing wrong? I'm unsure as to why I don't perfectly understand this, but I spent about an hour trying to come up with this.

感谢。

推荐答案

下面是你的算法:


  1. 如果n为0,返回X。

  2. 取1,和左移了N次,然后减去1.调用这个屏蔽

  3. 左移面具p乘以称之为 MASK2

  4. X具有MASK2的倒数。 y随面具,左偏差P倍。

  5. 或者这两个操作的结果,并返回该值。

  1. If n is 0, return x.
  2. Take 1, and left shift it n times and then subtract 1. Call this mask.
  3. Left shift mask p times call this mask2.
  4. And x with the inverse of mask2. And y with mask, and left shift p times.
  5. Or the results of those two operations, and return that value.

这篇关于K&放大器;与位运算 - [R运动混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆