What Does "(int) Value & 0x1, (int) Value & 0x2, (int) Value & 0x4, (int ...

    1. Home
    2. Questions
    3. Tags
    4. Users
    5. Jobs
    6. Companies
    7. Unanswered
  1. Teams

    Ask questions, find answers and collaborate at work with Stack Overflow for Teams.

    Try Teams for free Explore Teams
  2. Teams
  3. Ask questions, find answers and collaborate at work with Stack Overflow for Teams. Explore Teams

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams What does "(int) value & 0x1, (int) value & 0x2, (int) value & 0x4, (int) value & 0x8" mean?" Ask Question Asked 10 years, 4 months ago Modified 5 years, 6 months ago Viewed 51k times 11

code

The "value" ranges from 0 to 15 (its possible values). When will those 4 "if" conditions be met? If my (int)value = 2 does this mean 0010?

if ((int)value & 0x1) { //statement here } if ((int)value & 0x2) { //statement here } if ((int)value & 0x4) { //statement here } if ((int)value & 0x8) { //statement here } Share Improve this question Follow edited May 23, 2019 at 0:05 Sean McCarthy's user avatar Sean McCarthy 1014 bronze badges asked Jul 2, 2014 at 8:31 patrpatr 2
  • 3 Those are bitmasks checking for individual bits of value (read if(value & 0x4) as "Is the 3rd bit of value set (=1)). As you seemingly have problems understanding the code, I assume it is not yours. This (and the fact that you are not asking for review) makes this question off-topic for CR.SE. – Nobody moving away from SE Commented Jul 2, 2014 at 8:41
  • For better understanding, similar code that has been ported to C# will use the Enum.HasFlag method to test for bits. See: Enum.HasFlag. – rwong Commented Jul 2, 2014 at 13:18
Add a comment |

3 Answers 3

Sorted by: Reset to default Highest score (default) Date modified (newest first) Date created (oldest first) 12

Each number can be expressed as value = b0*2^0 + b1*2^1 + b2*2^2 + b3*2^3 + ... with each b being either 0 or 1 (these are the bits of the representation). This is the binary representation.

The binary AND (&) takes each of those b pair wise and performing AND on them. This has the following outputs:

0 & 0 = 0 0 & 1 = 0 1 & 0 = 0 1 & 1 = 1

Using powers of 2 (which have only a single bit on) we can isolate and test the individual bits:

  • value & 1 is true when value is odd {1, 3, 5, 7, 9, 11, 13, 15}.

  • value & 2 is true when value/2 is odd {2, 3, 6, 7, 10, 11, 14 ,15}.

  • value & 4 is true when value/4 is odd {4, 5, 6, 7, 12, 13, 14 ,15}.

  • value & 8 is true when value/8 is odd {8, 9, 10, 11, 12, 13, 14 ,15}.

The 0x prefex on the numbers means it should be interpreted as a hexadecimal number. It is a bit superfluous when you only go up to 0x8 but tells maintainers it is probably used as a bitmask.

Share Improve this answer Follow edited Jul 2, 2014 at 11:29 answered Jul 2, 2014 at 10:51 ratchet freak's user avatar ratchet freakratchet freak 26k2 gold badges64 silver badges100 bronze badges 2
  • 1 The wording may suggest that it can be extended to all numbers, which is not true: 8/6 is odd, while 8&6 yields false. – Sjoerd Commented Jul 2, 2014 at 11:13
  • @Sjoerd that's why I said "powers of 2" – ratchet freak Commented Jul 2, 2014 at 11:25
Add a comment | 5

These if-statements check if a specific bit of value is set.

The hexadecimal value 0x4, for example, has the 3rd bit from the right set to 1 and all other bits set to 0. When you use the binary-and operator (&) with two operants, the result will have all bits set to 0 except for those bits which are 1 in both operants.

So when you do the calculation value & 0x4, you either get binary 00000000 or binary 00000100, depending on whether or not the 3rd bit of value is 1 or 0. The first evaluates to false, and the second to true, so the if-block is only executed for values where the 3rd bit is set.

Share Improve this answer Follow edited Jul 2, 2014 at 13:18 answered Jul 2, 2014 at 13:13 Philipp's user avatar PhilippPhilipp 23.4k6 gold badges64 silver badges68 bronze badges Add a comment | 1

There are two interesting things to note here.

First, this is a common pattern for checking each of the low-order 4 bits of an integral value. The if condition is met if the corresponding bit is set. For the value 2 the bit pattern is indeed 0010.

The other more interesting question is why the (int) cast? Apart from the bad style of using C-casts in C++, no integer or character values require this cast. A bool makes no sense, a double/float would be converted to an integer temporary and it would be unusual to use literal values to test an enum. It might make sense with a pointer, but that would be a very specialised use. Conclusion: the cast makes no sense.

Share Improve this answer Follow answered Jul 2, 2014 at 14:18 david.pfx's user avatar david.pfxdavid.pfx 8,1472 gold badges22 silver badges45 bronze badges Add a comment |

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Software Engineering Stack Exchange. Learn more

Thanks for contributing an answer to Software Engineering Stack Exchange!

  • Please be sure to answer the question. Provide details and share your research!

But avoid …

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.

Draft saved Draft discarded

Sign up or log in

Sign up using Google Sign up using Email and Password Submit

Post as a guest

Name Email

Required, but never shown

Post Your Answer Discard

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

  • The Overflow Blog
  • We'll Be In Touch - A New Podcast From Stack Overflow!
  • The app that fights for your data privacy rights
  • Featured on Meta
  • More network sites to see advertising test
  • We’re (finally!) going to the cloud!
6 How does bit flipping / complementing work? 35 Is it a good practice to use smaller data types for variables to save memory? 4 Boundary conditions for testing 75 Using scoped enums for bit flags in C++ 9 C/C++: Which conversion warnings make sense in practice? 4 Explicitly define enum values, even if the default value is the same? 3 Overflow Exception Checking Problem 0 Getting an array index (0,1,2,..8) from bit masking value (1,2,4,8..256) without using log2(n). Maybe a design issue 2 What effects does memory space have on bitwise shifts?

Hot Network Questions

  • What is it called when you have a hobby where you're good enough at to impress others but you yourself know you're only beginning?
  • Why would you not issue orders to a facility?
  • Is Exception caught in the Service class a matter of preference?
  • The Talking Dog's Treats
  • Gifting $10k to my 17 year old nephew
  • What is China's official policy in case a third country attacks Taiwan?
  • Can Netanyahu use sovereign or diplomatic immunity as his defence to evade the arrest warrant issued by the ICC?
  • Is eating onion and garlic sin?
  • What kind of range hood do I need?
  • block nvme0n1: no uuid available providing old nguid - after disk cloning
  • Will Spirit trade with SAVEQ when it recovers?
  • Categories in which isomorphism of stalks does not imply isomorphism of sheaves
  • Nest "For Each" loops in Geometry Nodes
  • Why does C#'s Thread.MemoryBarrier() use "lock or" instead of mfence?
  • Does Windows 11 PIN Behavior Break Password Security Conventions?
  • Do switches try to keep track of Ethernet group membership?
  • How does time dilation affect the synchronization of clocks in different gravitational potentials?
  • Is partial correctness decidable?
  • How many colors do we need?
  • Quantum gravity and perturbative parameters
  • What is the origin of the term "Dog Character" in the context of fighting games?
  • Understanding Linux 'top' command: Memory vs Swap display format confusion
  • Why「记」for shop names?
  • Biasing common-source NMOS with active load and fixed Vgs
more hot questions Question feed Subscribe to RSS Question feed

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

lang-cpp

Từ khóa » C 0x8