Visual Basic 中的循环移位

Circular bit shift in Visual Basic

我编写了一个解决方案,我相信它可以在 Visual Basic 中进行循环位移。但是我是这门语言的新手,我不能 100% 确定这是有效的或实用的。有更好的方法吗?

如果你好奇的话,我正在尝试实现 ARIA cipher,我需要这个函数来实现。

Private Function CircularRotationLeft(ByVal bytes As Byte(), ByVal times As Integer) As Byte()
    Dim carry As Boolean = False
    If times < 0 Then
        Return Nothing
    End If
    While times > bytes.Length * 8
        times -= bytes.Length * 8
    End While
    If times = 0 Then
        Return bytes
    End If
    Array.Reverse(bytes)
    For index As Integer = 1 To times
        For Each bits As Byte In bytes
            If bits > 127 Then
                bits -= 128
                bits *= 2
                If carry Then
                    bits += 1
                End If
                carry = True
            Else
                bits *= 2
                If carry Then
                    bits += 1
                End If
                carry = False
            End If
        Next
        If carry Then
            bytes(0) += 1
        End If
    Next
    Array.Reverse(bytes)
    Return bytes
End Function

Private Function CircularRotationRight(ByVal bytes As Byte(), ByVal times As Integer) As Byte()
    Dim carry As Boolean = False
    If times < 0 Then
        Return Nothing
    End If
    While times > bytes.Length * 8
        times -= bytes.Length * 8
    End While
    If times = 0 Then
        Return bytes
    End If
    Array.Reverse(bytes)
    For index As Integer = 1 To times
        For Each bits As Byte In bytes
            If bits Mod 2 = 0 Then
                bits /= 2
                If carry Then
                    bits += 128
                End If
                carry = False
            Else
                bits /= 2
                If carry Then
                    bits += 128
                End If
                carry = True
            End If
        Next
        If carry Then
            bytes(0) += 128
        End If
    Next
    Array.Reverse(bytes)
    Return bytes
End Function

一种在 Visual Basic .NET 中旋转 32 位有符号整数的方法,应该不难适应您的需要:

Public Function RotateCircularLeft(n As Int32, nBits As Byte) As Int32
    Return (n << nBits) Or ((n >> (32 - nBits)) And (Not (-1 << nBits)))
End Function


Public Function RotateCircularRight(n As Int32, nBits As Byte) As Int32
    Return (n << (32 - nBits)) Or ((n >> nBits) And (Not (-1 << (32 - nBits))))
End Function

另请注意,调用函数 RotateCircularRight(x, n) 等同于调用 RotateCircularLeft(x, 32-n),因此您可以删除其中一个函数。

我还没有对哪种方法进行基准测试。