Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. How to check bits in a byte.

How to check bits in a byte.

Scheduled Pinned Locked Moved C / C++ / MFC
questionc++tutorial
3 Posts 3 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A Offline
    A Offline
    asp netProgrammer
    wrote on last edited by
    #1

    Hi all, i was wondering how do i check for individual bits in a byte. Like if i wanted to check if the 3rd bit in a byte was 1 or 0, how do i do that in c++?

    CPalliniC F 2 Replies Last reply
    0
    • A asp netProgrammer

      Hi all, i was wondering how do i check for individual bits in a byte. Like if i wanted to check if the 3rd bit in a byte was 1 or 0, how do i do that in c++?

      CPalliniC Online
      CPalliniC Online
      CPallini
      wrote on last edited by
      #2

      You can use binary operators (such as and) with proper operands. for example:

      bool checkbit2(unsigned char b)
      {
      if ( b & 0x04) return true else return false;
      }

      returns true if third bit (which is bit 2) of b is set (note the operand 0x04, that is binary 00000100). hope that helps.

      If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.

      In testa che avete, signor di Ceprano?

      1 Reply Last reply
      0
      • A asp netProgrammer

        Hi all, i was wondering how do i check for individual bits in a byte. Like if i wanted to check if the 3rd bit in a byte was 1 or 0, how do i do that in c++?

        F Offline
        F Offline
        Frank K
        wrote on last edited by
        #3

        Hi, count the bits: 8-7-6-5-4-3-2-1

        if(myByte & 0x4)
        {
          //the third bit is '1'
        }
        else
        {
          //the third bit is '0'
        }
        

        HTH

        1 Reply Last reply
        0
        Reply
        • Reply as topic
        Log in to reply
        • Oldest to Newest
        • Newest to Oldest
        • Most Votes


        • Login

        • Don't have an account? Register

        • Login or register to search.
        • First post
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • World
        • Users
        • Groups