## Bit Hacks

### August 9, 2013

A time-honored tradition among programmers is to hack a program to reduce the number of operations it takes, and a major component of that effort goes in to bit hacks, which we can define as dealing with data structures smaller than a single byte. Embedded systems programmers use bit hacks all of the time, as do game programmers and many others. We have three tasks today:

1) Determine the sign of an integer.

2) Determine if two integers have the same sign.

3) Determine the absolute value of an integer without branching.

Your task is to write bit hacks for the three tasks noted above; you may want to find multiple solutions for some of them. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Pages: 1 2

[…] today’s Programming Praxis exercise, our goal is to write three functions that use bit twiddling, namely […]

My Haskell solution (see http://bonsaicode.wordpress.com/2013/08/09/programming-praxis-bit-hacks/ for a version with comments):

1) if 1<<32 & int < int return "positive"

2) if int ^ int < 1<<32 return True

3) (1<<32 -1) & int

My same_sign isn’t that imaginative, but if you have a

`sign`

function thatreturns -1, 0, or 1, then

`abs(n)`

is just`sign(n) * n`

. Is multiplication moreexpensive than branching? Though I’ve written a decent amount of C++, I tend

to use it as a reasonably high-level language; I’m somewhat ruined when it

comes to bit-hackery.

Here is a C# solution.

Note that .NET uses two’s complement for signed integers.

At first glance the Abs function looks a little wrong, but in .Net the right shift operator ignores the highest order bit, this “isNegative” will be either 0 or -1.

Woops! I left a redundant multiplication of 1 in the posted code for Abs! lol.

…

int sign = ((n & IntegerMSBMask) >> 31) + ((~isNegative) & 1);

[/sourecode]

…