Tazze
Tazze

Reputation: 11

Circular bit shift in Visual Basic

I have coded a solution that I believe will work to make circular bit shifts in Visual Basic. However I'm new to the language, and I'm not 100% sure this is efficient or functional. Is there a better way of doing it?

In case you're curious, I'm trying to implement the ARIA cipher, and I need this function to do so.

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

Upvotes: 0

Views: 1864

Answers (1)

oscar
oscar

Reputation: 411

A way to rotate a 32 bit signed integer in Visual Basic .NET, shouldn't be difficult to adapt to your needs:

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

Also note that calling function RotateCircularRight(x, n) is equivalent to calling RotateCircularLeft(x, 32-n), so you could live deleting one of the functions.

I have not benchmarked which is the faster way.

Upvotes: 2

Related Questions