c# - 将 VB 翻译成 C#

标签 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 行中的每一个上都遇到了错误。错误是:

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));

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

感谢任何帮助。

最佳答案

按位运算符 always return int当操作数为 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# 之间有足够的特性,知道代码的作用以便您可以验证结果比仅仅修复编译器/语法错误更重要。

关于c# - 将 VB 翻译成 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31541631/

相关文章:

vb.net - 没有为一个或多个必需参数给出值。搜索期间出错

vb.net - VB.NET 中不使用定时器的表单转换

.net - OnPaint() 内部的 Graphics.Clear() 偶尔会导致通用 GDI+ 错误

java - 如何判断一个对象是否是 vector

c++ - 将 ML 代码转换为 C++

c# - OnClientClick 正在停止回发

c# - 我的 Loadbalancer 持有 ssl 证书,所以对我站点的所有请求都是 http。如何处理需要重定向的情况?

c# - 对如何组织我的类(class)有疑问

c# - 自己的WinForms控件闪烁且性能不佳

java - 有没有办法自动将 Groovy 转换为 Java?