3

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?

Greg
  • 667
  • 8
  • 19

2 Answers2

2

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.

ACVM
  • 1,497
  • 8
  • 14
  • The OP presupposes that `x` is a logical floating point number. You wouldn't use a logical floating point number to store flags. This is a reasonable use for bitwise-and, but in that case, the value would be logically integer the whole time or the flags are meaningless. – ShadowRanger Jan 04 '18 at 01:13
2

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.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271