将VB转换为C#

时间:2015-07-21 14:15:38

标签: c# vb.net code-translation

我有一个用VB编写的加密类,我试图将其转换为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行。错误是:

  

错误255无法将类型'int'隐式转换为'byte'。一个明确的   存在转换(你错过了演员吗?)

请原谅无知 - 我是一个亲戚C#新手,我尝试了以下但仍然有错误:

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

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

感谢任何帮助。

1 个答案:

答案 0 :(得分:9)

当操作数为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));
  

我不太清楚这段代码在做什么

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