2015-10-14 78 views
0

我已經編寫了一個解決方案,我相信它可以在Visual Basic中進行循環位移。不過,我對這門語言很陌生,我不能100%確定這是有效的或功能性的。有沒有更好的方法來做到這一點?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 
+0

請檢查標籤簡介,這不是[tag:vba]。 –

+0

抱歉的錯誤,並感謝您修復它! – Tazze

回答

0

旋轉在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),因此您可以實時刪除其中一項功能。

我還沒有基準哪個是更快的方法。

+0

這看起來好多了,謝謝! – Tazze