与数学幂加数相反的方法 [英] Opposite method of math power adding numbers
本文介绍了与数学幂加数相反的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有将布尔数组转换为整数的方法.看起来像这样
I have method for converting array of Booleans to integer. It looks like this
class Program
{
public static int GivMeInt(bool[] outputs)
{
int data = 0;
for (int i = 0; i < 8; i++)
{
data += ((outputs[i] == true) ? Convert.ToInt32(Math.Pow(2, i)) : 0);
}
return data;
}
static void Main(string[] args)
{
bool[] outputs = new bool[8];
outputs[0] = false;
outputs[1] = true;
outputs[2] = false;
outputs[3] = true;
outputs[4] = false;
outputs[5] = false;
outputs[6] = false;
outputs[7] = false;
int data = GivMeInt(outputs);
Console.WriteLine(data);
Console.ReadKey();
}
}
现在,我想使用相反的方法返回布尔值数组 到目前为止,由于我对.NET和C#的了解不足,所以我只对switch语句或每个可能的int值的条件进行了硬编码.
Now I want to make opposite method returning array of Booleans values As I am short with knowledge of .NET and C# until now I have only my mind hardcoding of switch statement or if conditions for every possible int value.
public static bool[] GiveMeBool(int data)
{
bool[] outputs = new bool[8];
if (data == 0)
{
outputs[0] = false;
outputs[1] = false;
outputs[2] = false;
outputs[3] = false;
outputs[4] = false;
outputs[5] = false;
outputs[6] = false;
outputs[7] = false;
}
//After thousand lines of coed
if (data == 255)
{
outputs[0] = true;
outputs[1] = true;
outputs[2] = true;
outputs[3] = true;
outputs[4] = true;
outputs[5] = true;
outputs[6] = true;
outputs[7] = true;
}
return outputs;
}
我知道必须有更简单的方法.
I know that there must be easier way.
推荐答案
您需要使用按位运算符:(已测试)
You need to use bitwise operators: (Tested)
public static bool[] GiveMeBool(int data) {
bool[] outputs = new bool[8];
for(int i = 0; i < 8; i++)
outputs[i] = (data & (1 << i)) == (1 << i);
return outputs;
}
您还可以使用按位运算符使原始的很多更快:(未经测试)
You can also use bitwise operators to make your original much faster: (Untested)
public static int GivMeInt(bool[] outputs) {
int data = 0;
for (int i = 0; i < 8; i++)
data += outputs[i] ? 1 << i : 0;
return data;
}
这篇关于与数学幂加数相反的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文