Visual Basic中的循环位移

时间:2015-10-14 08:05:56

标签: vb.net cryptography bit-manipulation bit-shift

我编写了一个解决方案,我相信它可以在Visual Basic中进行循环位移。但是,我是这门语言的新手,我并不是百分之百确定这是高效还是功能。有没有更好的方法呢?

如果你很好奇,我正在尝试实现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

1 个答案:

答案 0 :(得分:1)

在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),因此您可以实时删除其中一个函数。

我没有基准测试哪种方法更快。