【问题标题】:Translating VB to C#将VB翻译成C#
【发布时间】:2015-10-11 01:25:26
【问题描述】:

我有一个用 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));

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

感谢任何帮助。

【问题讨论】:

  • 试试:salt[0] = (byte)((salt[0] & 0xfc) | (saltLen & 0x3));

标签: c# vb.net code-translation


【解决方案1】:

当操作数为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# 之间有足够多的特性,因此了解代码的作用以便验证结果比仅仅修复编译器/语法错误更重要。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-13
    相关资源
    最近更新 更多