这个问题与逐位操作有什么关系? [英] What this question related bit-wise operation means?

查看:59
本文介绍了这个问题与逐位操作有什么关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不想要解决方案,只是想了解这个问题真正需要什么?



I don't want the solution, just want to understand what this question really asking for?

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.





一个例子真的有助于理解。提前致谢。



我的尝试:



Didn' t尝试了什么,但必须填写30个字符条件:P



An example would really help in understanding. Thanks in advance.

What I have tried:

Didn't tried anything, but have to fill for 30 character condition :P

推荐答案

OK:x是(推测)一个整数,这意味着它是一个集合(比如说) )32位构成数字:最右边的位是最不重要的,最左边的位是最重要的,它们从(通常)位0到位31编号,其中索引表示2的幂咬住了。如果你有一个整数有四位(为了使输入更简单):

OK: x is (presumably) an integer, which means it is a collection of (say) 32 bits which make up the number: the rightmost bit is the least significant, and the left most is the most significant, and they are numbered from (normally) bit 0 to bit 31, where the index indicates the power of two that the bit holds. If you pretent taht an integer has four bits (to make it simpler to type out):
Bit 0 == 2<sup>0</sup> == zero or one
Bit 1 == 2<sup>1</sup> == zero or two
Bit 2 == 2<sup>2</sup> == zero or four
Bit 3 == 2<sup>3</sup> == zero or eight.



你可以通过将两个幂加在一起来弥补(四位)数字可以容纳的整个值范围:


And you can make up the entire range of values that a (four bit) number can hold from those by adding the powers of two together:

Value  B3 B2 B1 B0
  0     0  0  0  0
  1     0  0  0  1
  2     0  0  1  0
  3     0  0  1  1
  4     0  1  0  0
  5     0  1  0  1
  6     0  1  1  0
  7     0  1  1  1
  8     1  0  0  0
  9     1  0  0  1
 10     1  0  1  0
 11     1  0  1  1
 12     1  1  0  0
 13     1  1  0  1
 14     1  1  1  0
 15     1  1  1  1

32位数的工作方式相同,但值范围很大!

问题是什么要求你做的是接受一个包含现有位的整数值,使用一个整数来告诉你从哪个位索引开始,要播放的位数和第二个值来获取新位。



所以如果n是6,你想要最右边的6位y:b31,b30,b29,b28, b27,b26

,如果p为2,你想要从b2:b8,b7,b6,b5,b4,b3,b2中删除x的六位,并用你的位替换它们从y中移除。



听起来很复杂,但事实并非如此。查看AND运算符&,OR运算符|和移位运算符>>和<< - 它们就是你应该需要的所有东西。

32 bit numbers work the same way, but with a HUGE range of values!
What the question is asking you to do is to accept an integer value containing existing bits, use an integer which tells you which bit index to start at, a number of bits to play with and a second value to get "new" bits from.

So if n is 6, you want the rightmost 6 bits of y: b31, b30, b29, b28, b27, b26
and if p is 2, you want to remove the six bits of x starting with b2: b8, b7, b6, b5, b4, b3, b2 and replace them with the bits you removed from y.

It sounds complex, but it isn't, not really. Look at the AND operator "&", the OR operator "|", and the shift operators >> and << - they are all you should need for this, pretty much.


这篇关于这个问题与逐位操作有什么关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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