Greg
Greg

Reputation: 707

Using a bitwise AND 1

If x is a floating point number, does

y = x & 1

have a purpose other than checking whether x is odd?

I just read Using bitwise OR 0 to floor a number and wonder, are there other interesting bitwise manipulations?

Upvotes: 3

Views: 116

Answers (2)

ShadowRanger
ShadowRanger

Reputation: 155683

If x is logically floating point (not intended to be an integer value before the test), & 1 has exactly one purpose: To determine if the truncated value of x is odd (it's a combined truncation and bitwise test). It's not saying if x is odd (-2.9 is neither odd nor even, nor is -3.9, and they give opposite results), and it's not just truncating (because it throws away all but one bit of data); the test is intrinsically combining both effects, and as such, is not useful for anything else when x is an arbitrary floating point value.

As other answer(s) mention, bitwise operations have other legitimate uses, e.g. cryptography, or repurposing an integer as a vector of boolean flags, but that's only relevant for logically integer values; performing floating point math and then relying on specific integer values after truncation, without rounding, is a terrible idea, and will bite you when the result ends up being X.9999999999999999999999994 when you expected it to be (and under "grade school" math, it would be) X+1.

Upvotes: 2

ACVM
ACVM

Reputation: 1527

You can use bitwise operators to encode options and flags.

ie. Encoding car features

automaticWindows = 0b1; // 1
manualTransmission = 0b10; // 2
hasAC = 0b100; // 4
hasHeater = 0b1000; // 8

If my car has automatic window and AC, but nothing else, then i'd do this:

myCarOptions = automaticWindows | hasAC;

Then to check if some random car has AC I can do:

if (randomCarOption & hasAC) {
  // do something... like turn on AC
}

At the end of the day bitwise operators simply allow you to do logic with the various bits which is the core of how computing works.

Upvotes: 2

Related Questions