Bitwise operator in pseudo-code

I advise against Andrey’s solution. He is right that in general pseudocode should be independent of a specific machine or language.

But this breaks down with bit operations. Bit operations do suggest a specific underlying architecture, and the bit operators follow an established nomenclature.

You don’t make the code more readable by ignoring this convention – in fact, you do the opposite.

I have the following commands defined in my thesis template:

\newcommand*\BitAnd{\mathbin{\&}}
\newcommand*\BitOr{\mathbin{|}}
\newcommand*\ShiftLeft{\ll}
\newcommand*\ShiftRight{\gg}
\newcommand*\BitNeg{\ensuremath{\mathord{\sim}}}

(The command names follow the naming convention of the algorithmicx package which I can recommend for typesetting algorithms.)

That said, you should second-guess your reason for using bit operations in the first place – often they are only used to achieve specific optimisations, in which case they have no place in a pseudo-code. On the other hand, sometimes (and it sounds as if this may be the case for you) they have a legitimate purpose.


Pseudocode has a different purpose compared to the actual programs. It should convey ideas, not implementation, and as such should be as close to the natural language as possible. Therefore I think it's not good to introduce programming language-specific syntax in the algorithm listing.

I suggest one of these options:

  • continue using algorithmicx and select a human-readable name for the operation: \State $x \gets \Call{ShiftLeft}{x, 3}$;
  • use the listings package and typeset the actual C++ program with comments.

For symbols, you can use \ll and \gg for shifting, and \lll, \ggg for rotating.

\documentclass{article}
\usepackage{amssymb}
\begin{document}

$a\land b$, $a\lor b$, $\lnot a$, $a\oplus b$

$a\ll b$, $a\gg b$, $a\lll b$, $a\ggg b$

\end{document}

enter image description here

You can also define some functions:

\usepackage{amsmath}
\DeclareMathOperator\shl{shl}% shift left
\DeclareMathOperator\shr{shr}% shift right
\DeclareMathOperator\rol{rol}% rotate left
\DeclareMathOperator\ror{ror}% rotate right

and use $\shl(a,n)$ etc. in the algorithm.

Tags:

Pseudocode