C ++中的“if(arg2& 1)”行(arg2是DWORD)等于C#中的“if(arg2& 1 == 0)”(arg2是Uint32),对吗?
我正在尝试将函数从C ++转换为C#,但是我收到错误:
Operator '&' cannot be applied to operands of type 'uint' and 'bool'
如果您能在整个功能中进一步了解其他任何错误,我也会感激不尽。
C ++
DWORD Func_X_4(DWORD arg1, DWORD arg2, DWORD arg3)
{
LARGE_INTEGER result = {1, 0};
LARGE_INTEGER temp1 = {0};
LARGE_INTEGER temp2 = {0};
LARGE_INTEGER temp3 = {0};
LARGE_INTEGER temp4 = {0};
for(int x = 0; x < 32; ++x)
{
if(arg2 & 1)
{
temp1.LowPart = arg3;
temp1.HighPart = 0;
temp2.QuadPart = temp1.QuadPart * result.QuadPart;
temp3.LowPart = arg1;
temp3.HighPart = 0;
temp4.QuadPart = temp2.QuadPart % temp3.QuadPart;
result.QuadPart = temp4.QuadPart;
}
arg2 >>= 1;
temp1.LowPart = arg3;
temp1.HighPart = 0;
temp1.QuadPart *= temp1.QuadPart;
temp2.LowPart = arg1;
temp2.HighPart = 0;
temp3.QuadPart = temp1.QuadPart % temp2.QuadPart;
arg3 = temp3.LowPart;
if(!arg2)
break;
}
return result.LowPart;
}
转换为C#
LARGE_INTEGER结构:
[StructLayout(LayoutKind.Explicit, Size = 8)]
public struct LARGE_INTEGER
{
[FieldOffset(0)]
public Int64 QuadPart;
[FieldOffset(0)]
public UInt32 LowPart;
[FieldOffset(4)]
public Int32 HighPart;
}
功能:
public static UInt32 X4(UInt32 arg1, UInt32 arg2, UInt32 arg3)
{
LARGE_INTEGER result = new LARGE_INTEGER();
result.LowPart = 1;
result.HighPart = 0;
LARGE_INTEGER temp1 = new LARGE_INTEGER();
LARGE_INTEGER temp2 = new LARGE_INTEGER();
LARGE_INTEGER temp3 = new LARGE_INTEGER();
LARGE_INTEGER temp4 = new LARGE_INTEGER();
for (int x = 0; x < 32; ++x)
{
if (arg1 & 1 ==0)
{
temp1.LowPart = arg3;
temp1.HighPart = 0;
temp2.QuadPart = temp1.QuadPart * result.QuadPart;
temp3.LowPart = arg1;
temp3.HighPart = 0;
temp4.QuadPart = temp2.QuadPart % temp3.QuadPart;
result.QuadPart = temp4.QuadPart;
}
arg2 >>= 1;
temp1.LowPart = arg3;
temp1.HighPart = 0;
temp1.QuadPart *= temp1.QuadPart;
temp2.LowPart = arg1;
temp2.HighPart = 0;
temp3.QuadPart = temp1.QuadPart % temp2.QuadPart;
arg3 = temp3.LowPart;
if (arg2==0)
break;
}
return result.LowPart;
}
这是我还不确定的事情:
提前致谢!
答案 0 :(得分:11)
你写的地方:
if(arg1&amp; arg2 == 0)
编译器理解:
if (arg1 & (arg2==0))
你应该写:
if ((arg1 & arg2) == 0)
这是C ++语句应该转换为C#的方式:
if (arg2 & 1) // C++ (arg2 is DWORD)
if ((arg2 & 1) != 0) // C# (arg2 is Uint32)
或者,以更通用的方式:
if (Flags & FlagToCheck) // C++
if ((Flags & FlagToCheck) != 0) // C#
在C / C ++中,0为假,其他一切都为真。
答案 1 :(得分:4)
DWORD
在C ++中为uint32_t
,因此在C#中为UInt32
。if(a & b)
转换为if((a & b) != 0)
。在!=
之前评估&
,因此&
表达式需要围绕它的括号。 if(x)
转换为if(x != 0)
&
在C#中是'按位和',就像在C ++中一样。答案 2 :(得分:1)
5 - 这意味着两者。因为LowPart和HighPart只是QuadPart内存的“窗口”,当result.LowPart == 1和Result.HighPart == 0时,result.QuadPart将等于1.