Java简单的按位操作
我们得到整数n、值v(v=0或1)和位置p。编写一系列运算符,修改n,将值v保持在n的二进制表示形式的p处。例如:Java简单的按位操作,java,bit-manipulation,operations,Java,Bit Manipulation,Operations,我们得到整数n、值v(v=0或1)和位置p。编写一系列运算符,修改n,将值v保持在n的二进制表示形式的p处。例如: n=5(00000101),p=3,v=1->13(00001101) n=5(00000101),p=2,v=0->1(00000001) 这是我的代码: int n1 = 35; int p1 = 3; int v = 1; n1 = n1 + (v << p1); System.out.println(n1); int n1=35; int p1=3; in
- n=5(00000101),p=3,v=1->13(00001101)
- n=5(00000101),p=2,v=0->1(00000001)
int n1 = 35;
int p1 = 3;
int v = 1;
n1 = n1 + (v << p1);
System.out.println(n1);
int n1=35;
int p1=3;
int v=1;
n1=n1+(v由于要将索引“设置”为一个值,因此需要两种操作之一
'and' will set 0 values at an index to 0, but won't work for 1 values
'or' will set 1 values at an index to 1, but won't work for 0 values
现在你需要做的就是把正确的数字放在正确的索引上。这可以通过移动1来实现
'<<' moves the 1 a number of places
现在我们可以在我们想要的索引中使用1或0,只需要使用if语句根据所需的操作选择正确的一个,并应用相应的和或或操作来设置我们想要的位。好的,我想这会起作用,但是如何在控制台上正确打印结果呢
// Swapping i and j: i ^= j, j ^= i, i ^= j;
// Getting the pth byte: (n >> p) & 1
// Setting the pth byte to v: (v == 0) ? (n & ~(1 << p)) : (n | 1 << p)
static int Exchange(int n, int i, int j)
{
n = ((n >> i) & 1 ^ (n >> j) & 1) == 0 ? (n & ~(1 << j)) : (n | 1 << j);
n = ((n >> i) & 1 ^ (n >> j) & 1) == 0 ? (n & ~(1 << i)) : (n | 1 << i);
n = ((n >> i) & 1 ^ (n >> j) & 1) == 0 ? (n & ~(1 << j)) : (n | 1 << j);
return n;
}
public static void main(String[] arguments)
{
int n = 56, p = 3, q = 24, k = 3;
while (k-- != 0) n = Exchange(n, p++, q++);
}
//交换i和j:i^=j,j^=i,i^=j;
//获取第pth字节:(n>>p)&1
//将第pth字节设置为v:(v==0)?(n&~(1i)&1^(n>>j)&1)==0?(n&~(1i)&1^(n>>j)&1)==0?(n&~(1i)&1^(n>>j)&1)==0?(n&~(1)使用总和,如果v=0,则添加0(移位不会改变它为0的事实),因此该值不会更改。您可能希望在那里查找其他操作。可能是位操作。我不回答此解决方案,因为这看起来确实像一个赋值,您应该能够自己实现。@bracco23它看起来确实像一个赋值,对于这类事情,我通常提供无代码的方法.希望你不介意。干杯。
'not' or '~' flips all the bits in a number
~00001000 yeilds 11110111
// Swapping i and j: i ^= j, j ^= i, i ^= j;
// Getting the pth byte: (n >> p) & 1
// Setting the pth byte to v: (v == 0) ? (n & ~(1 << p)) : (n | 1 << p)
static int Exchange(int n, int i, int j)
{
n = ((n >> i) & 1 ^ (n >> j) & 1) == 0 ? (n & ~(1 << j)) : (n | 1 << j);
n = ((n >> i) & 1 ^ (n >> j) & 1) == 0 ? (n & ~(1 << i)) : (n | 1 << i);
n = ((n >> i) & 1 ^ (n >> j) & 1) == 0 ? (n & ~(1 << j)) : (n | 1 << j);
return n;
}
public static void main(String[] arguments)
{
int n = 56, p = 3, q = 24, k = 3;
while (k-- != 0) n = Exchange(n, p++, q++);
}