将 VB 翻译成 C#

Translating VB to C#

我有一个用 VB 编写的加密 class,我正试图将其翻译成 C#。在VB代码中,有一段代码:

    ' Allocate byte array to hold our salt.
    Dim salt() As Byte = New Byte(saltLen - 1) {}

    ' Populate salt with cryptographically strong bytes.
    Dim rng As RNGCryptoServiceProvider = New RNGCryptoServiceProvider()

    rng.GetNonZeroBytes(salt)

    ' Split salt length (always one byte) into four two-bit pieces and
    ' store these pieces in the first four bytes of the salt array.
    salt(0) = ((salt(0) And &HFC) Or (saltLen And &H3))
    salt(1) = ((salt(1) And &HF3) Or (saltLen And &HC))
    salt(2) = ((salt(2) And &HCF) Or (saltLen And &H30))
    salt(3) = ((salt(3) And &H3F) Or (saltLen And &HC0))

我将其翻译成 C# 并得到以下结果:

    // Allocate byte array to hold our salt.
    byte[] salt = new byte[saltLen];

    // Populate salt with cryptographically strong bytes.
    RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

    rng.GetNonZeroBytes(salt);

    // Split salt length (always one byte) into four two-bit pieces and
    // store these pieces in the first four bytes of the salt array.
    salt[0] = ((salt[0] & 0xfc) | (saltLen & 0x3));
    salt[1] = ((salt[1] & 0xf3) | (saltLen & 0xc));
    salt[2] = ((salt[2] & 0xcf) | (saltLen & 0x30));
    salt[3] = ((salt[3] & 0x3f) | (saltLen & 0xc0));

当我尝试编译它时,我在分配给 salt[] 的 4 个代码块中的最后 4 行中的每一个上都遇到了错误。错误是:

Error 255 Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)

请原谅我的无知-我是一个相对的C#新手,我尝试了以下但仍然出错:

    salt[0] = ((salt[0] & 0xfc as byte) | (saltLen & 0x3 as byte));
    salt[0] = ((salt[0] & (byte)0xfc) | (saltLen & (byte)0x3));

我不太确定这段代码在做什么,这也许可以解释为什么我无法弄清楚如何修复它。

感谢任何帮助。

当操作数为 int 或更小时,位运算符 always return int。将结果转换为 byte:

salt[0] = (byte)((salt[0] & 0xfc) | (saltLen & 0x3));
salt[1] = (byte)((salt[1] & 0xf3) | (saltLen & 0xc));
salt[2] = (byte)((salt[2] & 0xcf) | (saltLen & 0x30));
salt[3] = (byte)((salt[3] & 0x3f) | (saltLen & 0xc0));

I am not quite sure what this code is doing

这比获得编译 的语法更重要。 VB 和 C# 之间有足够的特性,知道代码的作用以便您可以验证 结果 比仅仅修复 compiler/syntax 错误更重要。