Imports System
Module BitManipulation
' Prints the 8-bit binary representation of a number.
Sub PrintBinary(value As Long)
Console.WriteLine(Convert.ToString(value And &HFF, 2).PadLeft(8, "0"c))
End Sub
' Swaps odd and even bits in a 32-bit integer.
Function SwapOddAndEvenBits(n As Integer) As Long
' (binary: 101010...) to isolate odd bits.
Dim oddBits As Long = n And &HAAAAAAAA
' (binary: 010101...) to isolate even bits.
Dim evenBits As Long = n And &H55555555
Console.Write("oddBits: ")
PrintBinary(oddBits)
Console.Write("evenBits: ")
PrintBinary(evenBits)
' Right-shift odd bits by 1 to move them to even positions.
oddBits >>= 1
' Left-shift even bits by 1 to move them to odd positions.
evenBits <<= 1
Console.Write("oddBits Right-shift: ")
PrintBinary(oddBits)
Console.Write("evenBits Left-shift: ")
PrintBinary(evenBits)
' Combine shifted bits
Return oddBits Or evenBits
End Function
Sub Main()
Dim n As Integer = 90
' Original number in binary
PrintBinary(n)
Dim result As Long = SwapOddAndEvenBits(n)
' Final result in binary
PrintBinary(result)
End Sub
End Module
' run:
'
' 01011010
' oddBits: 00001010
' evenBits: 01010000
' oddBits Right-shift: 00000101
' evenBits Left-shift: 10100000
' 10100101
'