返回x,其中该开始在位置p设定为y的最右边的n位,而其它位不变的n位 [英] returns x with the n bits that begin at position p set to the rightmost n bits of y, leaving other bits unchanged

查看:441
本文介绍了返回x,其中该开始在位置p设定为y的最右边的n位,而其它位不变的n位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的解决方案

 得到y的最右边的n位
一个=〜(〜0℃;&下; N)及ÿ清洁x的从对开始n位
C =(〜0℃;&下; P |〜(〜0℃;≤(P-N + 1)))及X清洗过的n位设置为y的n个最右边的位
B | (一个或下;≤(P-N + 1))

这是相当长的语句。我们有一个更好的?

 
X = 0 1 1 1 0 1 1 0 1 1 1 0
P = 4
Y = 0 1 0 1 1 0 1 0 1 0
N = 3y的3最右边的位是0 1 0
它将替换x从第4位至第2位是1 1 1


解决方案

我写了类似之一:

 符号setbits(无符号X,INT P,诠释N,无符号Y)
{
  则返回(x&放大器;〜(〜(〜0℃;&下; N)下;≤(P + 1-N)))|((Y&放大器;〜(〜0℃;&下; N))≤;≤(的p + 1-N));
}

my solution

get the rightmost n bits of y
a = ~(~0 << n) & y

clean the n bits of x beginning from p
c = ( ~0 << p | ~(~0 << (p-n+1))) & x

set the cleaned n bits to the n rightmost bits of y
c | (a << (p-n+1))

it is rather long statements. do we have a better one?

 i.e
x = 0 1 1 1 0 1 1 0 1 1 1 0
p = 4
y = 0 1 0 1 1 0 1 0 1 0 
n = 3

the 3 rightmost bits of y is 0 1 0 
it will replace x from bits 4 to bits 2 which is 1 1 1

解决方案

I wrote similar one:

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

这篇关于返回x,其中该开始在位置p设定为y的最右边的n位,而其它位不变的n位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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