[英]Shifting 4 bits using a single number
I have to write a method that takes in an integer as a parameter (0, 1, 2, or 3). 我必须编写一个将整数作为参数(0、1、2或3)的方法。 I have to use that to create a bitmask with a 0. So, if the parameter is 0, than the bitmask will be
FFF0
, for 1: FF0F
, 2: F0FF
, 3: 0FFF
. 我必须用它来创建具有0,所以一个位掩码,如果参数是0,比位掩码将
FFF0
,对于1: FF0F
,2: F0FF
,3: 0FFF
。 I am trying not to hardcode it. 我正在尝试不对其进行硬编码。
What I have tried, but it only works partially: 我尝试过的方法,但只能部分起作用:
int bob = 0xFFFF;
int multi = 2;
multi = multi << param;
this works with 1 and 2, and for even those, it makes it 0xFF00
, and 0xF000
. 这适用于1和2,即使对于那些,也使其
0xF000
0xFF00
和0xF000
。
I am trying not to use multiplication either (that would make it a lot easier, so I don't want to use it). 我也尝试不使用乘法(这会使乘法容易得多,所以我不想使用它)。
我会说:
0xFFFF - (0xF << (param * 4))
Something like this: 像这样:
bitmask = 0xFFFF;
bitmaskmask = 0xF;
bitmaskmask = bitmaskmask << parameter * 4;
bitmask = bitmask ^ bitmaskmask;
Given your inputs, you can achieve what you are looking for using the bitwise XOR operation as follows: 有了您的输入,您可以使用按位XOR操作实现所需的目标,如下所示:
xorMask = 0x000F << (4*multi) ;
result = bob ^ xorMask ;
This creates an XOR mask with 1 bits in the appropriate portion of the 16 bit value, then XORing it with the input to 0 those bits in the output. 这将在16位值的适当部分中创建一个具有1位的XOR掩码,然后将其与输入进行异或,将输出中的那些位设为0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.