gpt4 book ai didi

c# - 将 VB 翻译成 C#

转载 作者:太空宇宙 更新时间:2023-11-03 17:50:15 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com