How to resolve the algorithm Bitwise operations step by step in the Common Lisp programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Bitwise operations step by step in the Common Lisp programming language
Table of Contents
Problem Statement
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.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Bitwise operations step by step in the Common Lisp programming language
Source code in the common programming language
(defun bitwise (a b)
(print (logand a b)) ; AND
(print (logior a b)) ; OR ("ior" = inclusive or)
(print (logxor a b)) ; XOR
(print (lognot a)) ; NOT
(print (ash a b)) ; arithmetic left shift (positive 2nd arg)
(print (ash a (- b))) ; arithmetic right shift (negative 2nd arg)
; no logical shift
)
(defun shl (x width bits)
"Compute bitwise left shift of x by 'bits' bits, represented on 'width' bits"
(logand (ash x bits)
(1- (ash 1 width))))
(defun shr (x width bits)
"Compute bitwise right shift of x by 'bits' bits, represented on 'width' bits"
(logand (ash x (- bits))
(1- (ash 1 width))))
(defun rotl (x width bits)
"Compute bitwise left rotation of x by 'bits' bits, represented on 'width' bits"
(logior (logand (ash x (mod bits width))
(1- (ash 1 width)))
(logand (ash x (- (- width (mod bits width))))
(1- (ash 1 width)))))
(defun rotr (x width bits)
"Compute bitwise right rotation of x by 'bits' bits, represented on 'width' bits"
(logior (logand (ash x (- (mod bits width)))
(1- (ash 1 width)))
(logand (ash x (- width (mod bits width)))
(1- (ash 1 width)))))
You may also check:How to resolve the algorithm Generator/Exponential step by step in the Lingo programming language
You may also check:How to resolve the algorithm Constrained random points on a circle step by step in the Quackery programming language
You may also check:How to resolve the algorithm Arithmetic/Complex step by step in the Ada programming language
You may also check:How to resolve the algorithm Roman numerals/Decode step by step in the Ceylon programming language
You may also check:How to resolve the algorithm Averages/Root mean square step by step in the Objeck programming language