代码之家  ›  专栏  ›  技术社区  ›  Happy Day

将字节为[]的函数从C#转换为C++[闭合]

  •  1
  • Happy Day  · 技术社区  · 7 年前

    我的函数有原始C#代码: 它们就像一个符咒,我将把它们转换成C++

        public static byte[] EncryptBlock(byte[] filebuffer)
        {
            int a, i, j, k, tmp;
            int[] key, box;
            byte[] cipher;
    
            key = new int[KeyBoxLength];
            box = new int[KeyBoxLength];
            cipher = new byte[filebuffer.Length];
    
            for (i = 0; i < KeyBoxLength; i++)
            {
                key[i] = XorContentLock[i % XorContentLock.Length];
                box[i] = i;
            }
            for (j = i = 0; i < KeyBoxLength; i++)
            {
                j = (j + box[i] + key[i]) % 256;
                tmp = box[i];
                box[i] = box[j];
                box[j] = tmp;
            }
            for (a = j = i = 0; i < filebuffer.Length; i++)
            {
                a++;
                a %= KeyBoxLength;
                j += box[a];
                j %= KeyBoxLength;
                tmp = box[a];
                box[a] = box[j];
                box[j] = tmp;
                k = box[((box[a] + box[j]) % KeyBoxLength)];
                cipher[i] = (byte)(filebuffer[i] ^ k);
            }
            return cipher;
        }
    

    这就是它们在C++上的外观,但我不知道为什么会出现这些错误。

    std::string Conversion::EncryptBlock(std::string& buffer)
    {
        int32 a, i, j, k, tmp;
        int key[256];
        int box[256];
        BYTE* cipher = new BYTE[buffer.length];
        for (i = 0; i < KeyBoxLength; i++)
        {
            key[i] = XorFileLock[i % 16];
            box[i] = i;
        }
        for (j = i = 0; i < KeyBoxLength; i++)
        {
            j = (j + box[i] + key[i]) % 256;
            tmp = box[i];
            box[i] = box[j];
            box[j] = tmp;
        }
        for (a = j = i = 0; i < buffer.length; i++)
        {
            a++;
            a %= KeyBoxLength;
            j += box[a];
            j %= KeyBoxLength;
            tmp = box[a];
            box[a] = box[j];
            box[j] = tmp;
            k = box[((box[a] + box[j]) % KeyBoxLength)];
            cipher[i] = (byte)(buffer[i] ^ k);
        }
        std::string ret(reinterpret_cast< char const* >(cipher));
        delete[] cipher;
    
        return ret;
    }
    

    当我编译它时,我得到了:

    enter image description here

    那么,我做错了什么?请解释一下,为什么?它应该是怎样的? 另一个例子: enter image description here

    1 回复  |  直到 7 年前
        1
  •  3
  •   Miles Budnek    7 年前

    std::string::length std::string unsigned int

    BYTE* cipher = new BYTE[buffer.length()];
                                      // ^^ Here
    

    与您的问题无关,您应该使用 std::vector<BYTE> 而不是管理自己的原始阵列。您可以更改 cipher

    std::vector<BYTE> cipher(buffer.length());
    

    ret

    std::string ret(cipher.begin(), cipher.end());
    

    那你就不用记得了 delete[] cipher .没有真正的理由复制 ret公司 密码 std::string cipher(buffer.length(), '\0'); return cipher; 直接地