
Basic Data Operation

This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:


Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses




Task

Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.

All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.

If any operation is not available in your language, note it.




 
' FB 1.05.0 Win64 (Note the (U)Integer type is 64 bits)
 
' FB doesn't have built-in logical shift right or rotation operators
' but, as they're not difficult to implement, I've done so below.
 
Function lsr(x As Const Integer, y As Const Integer) As Integer
  Dim As UInteger z = x
  Return z Shr y
End Function
 
Function rol(x As Const Integer, y As Const UInteger) As Integer
  Dim z As Integer = x
  Dim high As Integer
  For i As Integer = 1 To y
    high = Bit(z, 63)
    For j As Integer = 62 To 0 Step -1
      If Bit(z, j) Then
        z = BitSet(z, j + 1)
      Else
        z = BitReset (z, j + 1)
      End If
    Next j
    If high Then
      z = BitSet(z, 0)
    Else
      z = BitReset(z, 0)
    End If
  Next i
  Return z
End Function
 
Function ror(x As Const Integer, y As Const UInteger) As Integer
  Dim z As Integer = x
  Dim low As Integer
  For i As Integer = 1 To y
    low = Bit(z, 0)
    For j As Integer = 1 To 63 
      If Bit(z, j) Then
        z = BitSet(z, j - 1)
      Else
        z = BitReset (z, j - 1)
      End If
    Next j
    If low Then
      z = BitSet(z, 63)
    Else
      z = BitReset(z, 63)
    End If
  Next i
  Return z
End Function  
 
Sub bitwise(x As Integer, y As Integer)
  Print "x       = "; x
  Print "y       = "; y
  Print "x AND y = "; x And y
  Print "x OR y  = "; x Or y
  Print "x XOR y = "; x XOr y
  Print "NOT x   = "; Not x
  Print "x SHL y = "; x Shl y
  Print "x SHR y = "; x Shr y
  Print "x LSR y = "; lsr(x, y)
  Print "x ROL y = "; rol(x, y)
  Print "x ROR y = "; ror(x, y)
End Sub
 
bitwise -15, 3
Print
Print "Press any key to quit"
Sleep