Bri*_*oss 1 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))
Run Code Online (Sandbox Code Playgroud)
我把它翻译成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));
Run Code Online (Sandbox Code Playgroud)
当我尝试编译这个时,我在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));
Run Code Online (Sandbox Code Playgroud)
我不太清楚这段代码在做什么,这或许可以解释为什么我无法弄清楚如何修复它.
任何帮助表示赞赏.
当操作数为或更小时,按位运算符总是返回intint.将结果投射到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));
Run Code Online (Sandbox Code Playgroud)
我不太清楚这段代码在做什么
获得编译的语法更重要.VB和C#之间有足够的特性,知道代码的作用,以便您可以验证结果比仅修复编译器/语法错误更重要.