我们说我有一个15岁的c。 c可以分成a = 7和b = 13。 这是因为| b = c。 我正在尝试编写一个函数,通过仅输入c作为输入来找到a和b的一种可能组合。
class Program
{
static void Main(string[] args)
{
int data = 560;
int[] v = FindBitshiftOr(data);
Console.WriteLine("{0} << {1} = {2}", v[0], v[1], v[0] | v[1]);
Console.ReadKey();
}
private static Random r = new Random();
private static int[] FindBitshiftOr(int value)
{
int[] d = new int[2];
int a = r.Next(0, value);
int c = r.Next(0, value);
int b = ~a;
d[0] = a;
d[1] = b | c;
return d;
}
}
这是我的尝试,但它总是返回-1,有人可以解释我的错误吗?
答案 0 :(得分:2)
您得到-1,因为您将所有位设置为1
,并将OR与数字及其否定相加。
代码的基本部分是:
int a = 42; // you get random number, but it does not matter here.
int b = ~a | c; // "| c" part just possibly add more 1s
result = a | b; // all 1s as it essentially (a | ~a) | c
分隔位的正确方法是x & ~mask
- 请参阅Most common C# bitwise operations on enums中的链接/示例。
答案 1 :(得分:2)
试试这段代码。并且操作用于提取相同的位。我不知道C#所以我无法输入确切的代码。逻辑采用随机位掩码和AND c
的位与该位掩码和该位掩码的反转。得到的两个数字将是您需要的数字。
int c = 4134;
int a = r.Next(0, value);
int first_num = c & a;
int second_num = c & ~a;
int check_c = first_num | second_num
check_c
和c
应该相等