首页 > 解决方案 > 如何将 C++ 转换为 C# 代码而 statmernt 代码递减

问题描述

我正在尝试的是转换 C++ 代码

 while (n--) if (c & 0x80000000) c = (c << 1) ^ p2; else c <<= 1;

进入c#

c ++中的整个代码是:

#include "stdafx.h"
int main()
{
    unsigned long c, c2, p2, pol = 0xEDB88320;
    long n, k;
    {
        printf("CRC32 Adjuster (c) 2001 by RElf @ HHT/2\n");

        printf("Length of data: "); scanf_s("%ld", &n);

        printf("Offset to patch: "); scanf_s("%ld", &k);

        n = (n - k) << 3;

        printf("Current CRC32: 0x"); scanf_s("%x", &c);

        printf("Desired CRC32: 0x"); scanf_s("%x", &c2);

        c ^= c2;

        p2 = (pol << 1) | 1;

        while (n--) if (c & 0x80000000) c = (c << 1) ^ p2; else c <<= 1;

printf("XOR masks:%02X%02X%02X%02X\n", c & 0xff, (c >> 8) & 0xff, (c >> 16) & 0xff, c >> 24);
    }
    return 0;
}

我在翻译成 c# 时尝试过的内容:

using System;

namespace crc323_fake
{
    class Program
    {
        static void Main(string[] args)
        {
            long c, c2, p2, pol = 0xEDB88320;
            long n, k;
            {
                n = 3440;
                k = 3436;
                n = (n - k) << 3;
                c = 0x73CBFFB5;
                c2 = 0x7D096252;
                c ^= c2;

                p2 = (pol << 1) | 1;
                while (n != 0)
                {
                    n = n - 1;
                    if( c &  0x80000000 )   // getting error here can't implicitly convert long to bool
                    {
                    }
                }

                Console.WriteLine("XOR masks:%02X%02X%02X%02X\n", c & 0xff, (c >> 8) & 0xff, (c >> 16) & 0xff, c >> 24);
                while (1) ;
            }
            
        }
    }
}

我摆脱了打印语句并为变量提供了直接值,但我坚持

        while (n != 0)
        {
            n = n - 1;
            if( c &  0x80000000 )
          {
          }
        }

if( c & 0x80000000 ) 给我错误“不能隐式地将 long 转换为 bool” 抱歉,如果这个问题似乎是新手,我真的是 c# 新手

标签: c#c++

解决方案


在 C++ 中,非 nul 整数转换为 true。

所以你必须在这里明确:

if (c &  0x80000000)

变成

if ((c &  0x80000000) != 0)

演示


推荐阅读