int p1 = 1010;
int p2 = 0110;
int p3 = method1( p1,p2);
如果要p3 最后结果为0010,请问这个method1的方法该如何实现?也不一定是整数,只要能实现,两个串,能够实现相同位都是1才变成1,其他都变成0,就可以了,想了很久,想不出来啊,请大家帮忙!
int p2 = 0110;
int p3 = method1( p1,p2);
如果要p3 最后结果为0010,请问这个method1的方法该如何实现?也不一定是整数,只要能实现,两个串,能够实现相同位都是1才变成1,其他都变成0,就可以了,想了很久,想不出来啊,请大家帮忙!
{
int p1 = 1010;
int p2 = 0110;
int p3 = MyClass.method1( p1,p2);
Console.WriteLine(p3.ToString("d4"));
}
public static int method1(int p1, int p2)
{
int n1 = Convert.ToInt32(p1.ToString(), 2);
int n2 = Convert.ToInt32(p2.ToString(), 2);
int result = n1 & n2;
return Int32.Parse(Convert.ToString(result, 2));
}
结果:
0010
string s2 = "0110";int i1 = Convert.ToInt32(s1, 2);
int i2 = Convert.ToInt32(s2, 2);
int i3 = i1 & i2;
string s3 = Convert.ToString(i3, 2);
s3 = "0000" + s3;
s3 = s3.Substring(s3.Length - 4, 4);
MessageBox.Show(s3);
private string methodCompare(string pow1,string pow2)
{
string str1 = "";
if(pow1.Length==pow2.Length)
{
char[] aa = pow1.ToCharArray();
char[] bb = pow2.ToCharArray();
char[] cc = new char[aa.Length];
for(int i=0;i<aa.Length;i++)
{
int a1 = int.Parse(aa[i].ToString());
int b1 = int.Parse(bb[i].ToString()); int c1 = (a1&b1);
cc[i] = char.Parse( c1.ToString());
}
for(int i=0;i<cc.Length;i++)
{
str1 += cc[i].ToString();
}
} return str1;
}
楼上几位的方法我调试过了,通不过,提示
未处理的“System.FormatException”类型的异常出现在 mscorlib.dll 中。其他信息: 未找到任何可分析的位。
{
string c="";
for(int i=0;i<a.Length;i++)
{
if(a[i]=='1'&&b[i]=='1')
c+="1";
else
c+="0";
}
return c;
}
未处理的“System.FormatException”类型的异常出现在 mscorlib.dll 中。其他信息: 未找到任何可分析的位。
----------------------------------------------------------------------不会吧,我可是通过测试了的。
比如
int a = 0x09; //对应1011
int b = 0x03; //0110 保留高2位,意思是 0不舍弃然后 把 int c = a & b;
toBinString(c)
保留高8位,如果想保留高4位就 return new string('0',4-bin.Length) + bin; public static string toBinString(int dec)
{
//如果大于8bit,直接返回 8 bit 最大值
if(dec>255){return "11111111";}
string bin = "";
while(dec > 1)
{
bin = dec%2 + bin;
dec /= 2;
}
bin = dec + bin;
//用0补上确少的高位,到8为止
return new string('0',8-bin.Length) + bin;
你要是赋一个int p1 = 1234;肯定出错
public static void Main()
{
int p1 = 10;
int p2 = 0110;
int p3 = MyClass.method1( p1,p2);
Console.WriteLine(p3.ToString("d4"));
string s1 = "1010";
string s2 = "0110";
string s3 = MyClass.method1(s1, s2);
Console.WriteLine(s3);
}
public static int method1(int p1, int p2)
{
int n1 = Convert.ToInt32(p1.ToString(), 2);
int n2 = Convert.ToInt32(p2.ToString(), 2);
int result = n1 & n2;
return Int32.Parse(Convert.ToString(result, 2));
}
public static string method1(string s1, string s2)
{
int n1 = Convert.ToInt32(s1, 2);
int n2 = Convert.ToInt32(s2, 2);
int result = n1 & n2;
return Convert.ToString(result, 2);
}结果:
0010
10