jaaytbe
jaaytbe

Reputation: 43

View a specific bit of a hex number?

I am working on a piece of logic that will teach me how bitops and bit manipulation works, and I am trying to view a specific bit of a given hex number. For example f0f0 has the following bit value 1111000011110000. So let's say I am trying to view the i^th bit, let's say for example i choose the 4th position, my logic should return 1. I tried doing it by doing this logic:

unsigned int desiredBit = hex & (1 << decimal);
      printf("%x\n", desiredBit);

This seems to work any time a bit is 0, but whenever a bit is 1, it spits out a multiple of 10. I assumed that doing a << would just take me to that position but i guess I was wrong. Any guidance on how to fix my logic?

Upvotes: 0

Views: 1451

Answers (2)

Govind Parmar
Govind Parmar

Reputation: 21572

You're getting the numerical value of the number with just that one that bit set, which isn't exactly 1 unless it's the LSB.

For example, with the number 0b11100101, if you mask out the second-MSB (0b11100101 & 0b01000000), the result is 0b01000000 which is 64 in base 10.

If you want the result to be either 1 or 0, you can perform !! on the entire operation, i.e. printf("%d\n", !!(num1 & num2)); will always either be 1 if the bit was set or 0 if it was not.

Upvotes: 0

Stephan Lechner
Stephan Lechner

Reputation: 35164

You are getting a multiple of 2 actually, i.e. the "weight" of this particular bit if it is set, 0 otherwise. If you just want to know if it is set or not, check if this weight is something != 0 or not:

Try

unsigned int setOrNot = (hex & (1 << decimal)) != 0;

Upvotes: 1

Related Questions