Computer Science

Bitwise Operators in C

Bitwise operators in C are used to manipulate individual bits of data. These operators include AND, OR, XOR, NOT, left shift, and right shift. They are commonly used in low-level programming, such as in embedded systems and device drivers.

Written by Perlego with AI-assistance

8 Key excerpts on "Bitwise Operators in C"

  • Embedded Systems
    eBook - ePub

    Embedded Systems

    A Contemporary Design Tool

    • James K. Peckol(Author)
    • 2019(Publication Date)
    • Wiley
      (Publisher)
    struct data type provides the ability to mix different data types in the same container and to treat that collection as a single entity.
    Pointers to functions are a powerful mechanism that enables a function to be passed to another block of code and evaluated in the local context. Interrupts provide support for accepting and managing asynchronous events originating from inside or outside of the ‐system.

    7.2 Bitwise Operators

    Bitwise Operators in C are more commonly found in the embedded systems developer's tool box rather than in that of the traditional application developer's. Such operators are intended for work at the hardware level – that is, with the registers and input or output ports on a target machine.
    The bitwise operators are summarized in Table 7.1 .
    Table 7.1
    Bitwise Operators
    Operator Meaning Description
    Shift
    > Logical shift right Operand shifted positions are filled with 0's
    < Logical shift left Operand shifted positions are filled with 0's
    Logical
    & Bitwise AND
    | Bitwise inclusive OR
    ^ Bitwise exclusive OR
    Bitwise negation
    unsigned integral type,
    unsigned char
    unsigned short, unsigned int
    When working at the bit level, often all of the bits in a word are important because they generally represent the state of some signal in the hardware of the machine. Consequently, the underlying operand type should be an unsigned integral type such as an unsigned char, unsigned short, or unsigned int
  • C Programming
    eBook - ePub

    C Programming

    Learn to Code

    Figure 6.16 .
    Figure 6.15 Nested conditional operator example.
    Figure 6.16 Execution process of the example in Figure 6.15.
    According to the value of a and b, the statement a > b becomes false, so the false part of the statement is executed as shown in Figure 6.16. Again b > c becomes true so 30 will be returned and hence is assigned to the variable ans. So, the output will be 30.

    6.8 Bitwise Operators

    Each digit in a binary number system is called a bit, and is either 0 or 1. As the name suggests, the computer uses a bitwise operator to operate on binary numbers. The C language provides six bitwise operators; Table 6.6 shows their symbols and meanings.
    Table 6.6 Bitwise Operators
    Sl. No. Operator Symbol Meaning
    1 & Bitwise AND
    2 | Bitwise OR
    3 ^ Bitwise XOR
    4 ~ One’s complement
    5 << Left-shift
    6 >> Right-shift

    6.8.1 Bitwise AND, OR, XOR

    Like the logical AND operator, bitwise AND follows the same truth table and requires two operands. But the working procedure of this operator is different. The former works on any value and returns either 0 or 1, but the latter converts the value to its corresponding binary number and performs the AND operation bit by bit.
    Let us take an example (Figure 6.17 ) to show the differences between their working.
    Figure 6.17 Example showing the difference between the logical AND and Bitwise AND operators.
    Similarly, for the OR and XOR operators, the working procedure is the same. Students are encouraged to modify the above program and check for the OR and XOR operators. The XOR operator works as per the truth table shown in Table 6.7
  • Ivor Horton's Beginning Visual C++ 2012
    • Ivor Horton(Author)
    • 2012(Publication Date)
    • Wrox
      (Publisher)
    char , as well as the unsigned variants of these, can be used. The bitwise operators are useful in programming hardware devices, where the status of a device is often represented as a series of individual flags (that is, each bit of a byte may signify the status of a different aspect of the device), or for any situation where you might want to pack a set of on-off flags into a single variable. You will see them in action when you look at input/output in detail, where single bits are used to control various options in the way data is handled.
    There are six bitwise operators:
    & bitwise AND | bitwise OR ^ bitwise exclusive OR
    ~ bitwise NOT >> shift right << shift left
    The following sections explain how each of them works.

    The Bitwise AND

    The bitwise AND, & , is a binary operator that combines corresponding bits in its operands in a particular way. If both corresponding bits are 1, the result is a 1 bit, and if either or both bits are 0, the result is a 0 bit.
    The effect of a particular binary operator is often shown using what is called a truth table. This shows, for various possible combinations of operands, what the result is. The truth table for & is as follows:
    Bitwise AND 0 1
    0 0 0
    1 0 1
    For each row and column combination, the result of & combining the two is the entry at the intersection of the row and column. You can see how this works in an example:
    char letter1 = 'A', letter2 = 'Z', result = 0; result = letter1 & letter2;
    You need to look at the bit patterns to see what happens. The letters 'A' and 'Z' correspond to hexadecimal values 0x41 and 0x5A, respectively. The way in which the bitwise AND operates on these two values is shown in Figure 2-7 .
    FIGURE 2-7
    You can confirm this by looking at how corresponding bits combine with & in the truth table. After the assignment, result will have the value 0x40, which corresponds to the character '@' .
    Because the & produces zero if either bit is zero, you can use this operator to make sure that unwanted bits are set to 0 in a variable. You achieve this by creating what is called a “mask” and combining it with the original variable using & . You create the mask by specifying a value that has 1 where you want to keep a bit, and 0 where you want to set a bit to zero. The result of AND-ing the mask with another integer will be 0 bits where the mask bit is 0, and the same value as the original bit in the variable where the mask bit is 1. Suppose you have a variable letter of type char where, for the purposes of illustration, you want to eliminate the high-order 4 bits, but keep the low-order 4 bits. This is easily done by setting up a mask as 0x0F and combining it with the value of letter using &
  • C++ For Dummies
    eBook - ePub
    • Stephen R. Davis(Author)
    • 2014(Publication Date)
    • For Dummies
      (Publisher)
    If you really want to, you can write binary numbers in C++ '14 using the prefix ‘0b'. Thus, 123 becomes 0b01111011.

    Performing Bitwise Logical Operations

    All C++ numbers can be expressed in binary form. Binary numbers use only the digits 1 and 0 to represent a value. Table 4-2 defines the set of operations that work on numbers one bit at a time, hence the term bitwise operators.
    Table 4-2 Bitwise Operators
    Operator Function
    ~ NOT: toggle each bit from 1 to 0 and from 0 to 1
    & AND each bit of the left-hand argument with that on the right
    | OR each bit of the left-hand argument with that on the right
    ^ XOR (exclusive OR) each bit of the left-hand argument with that on the right
    Bitwise operations can potentially store a lot of information in a small amount of memory. Many traits in the world have only two possibilities — that are either this way or that way. You are either married or you’re not. You are either male or female (at least that’s what my driver’s license says). In C++, you can store each of these traits in a single bit — in this way, you can pack 32 separate binary properties into a single 32-bit int.
    In addition, bit operations can be extremely fast. No performance penalty is paid for that 32-to-1 savings.
    Even though memory is cheap these days, it’s not unlimited. Sometimes, when you’re storing large amounts of data, this ability to pack a whole lot of properties into a single word is a big advantage.

    The single-bit operators

    The bitwise operators — AND (&), OR (|) and NOT (~) — perform logic operations on single bits. If you consider 0 to be false and 1 to be true (it doesn’t have to be this way, but it’s a common convention), you can say things like the following for the NOT operator:
      ~ 1 (true)  is 0 (false)~ 0 (false) is 1 (true) The AND operator is defined as following:   1 (true) & 1 (true)  is 1 (true)1 (true) & 0 (false) is 0 (false) It’s a similar situation for the OR operator:   1 (true)  | 0 (false) is 1 (true)0 (false) | 0 (false) is 0 (false)
    The definition of the AND operator appears in Table 4-3
  • Assembly Language Step-by-Step
    eBook - ePub

    Assembly Language Step-by-Step

    Programming with Linux

    • Jeff Duntemann(Author)
    • 2011(Publication Date)
    • Wiley
      (Publisher)
    SHR . (There are a few others that I will not be discussing in this book.)
    Bit Numbering
    Dealing with bits requires that we have a way of specifying which bits we're dealing with. By convention, bits in assembly language are numbered, starting from 0, at the least-significant bit in the byte, word, or other item we're using as a bitmap. The least-significant bit is the one with the least value in the binary number system. It's also the bit on the far right if you write the value down as a binary number in the conventional manner.
    I've shown this in Figure 9.1 , for a 16-bit word. Bit numbering works exactly the same way no matter how many bits you're dealing with: bytes, words, double words, or more. Bit 0 is always on the right-hand end, and the bit numbers increase toward the left
    Figure 9.1 Bit numbering
    When you count bits, start with the bit on the right, and number them from 0. “It's the Logical Thing to Do, Jim…”
    Boolean logic sounds arcane and forbidding, but remarkably, it reflects the realities of ordinary thought and action. The Boolean operator AND , for instance, pops up in many of the decisions you make every day of your life. For example, to write a check that doesn't bounce, you must have money in your checking account AND checks in your checkbook. Neither alone will do the job. You can't write a check that you don't have, and a check without money behind it will bounce. People who live out of their checkbooks (and they always seem to end up ahead of me in the checkout line at Safeway) must use the AND operator frequently.
    When mathematicians speak of Boolean logic, they manipulate abstract values called True and False. The AND operator works like this. Condition1 AND Condition2 will be considered True if both
  • Microcontroller Programming
    eBook - ePub
    • Julio Sanchez, Maria P. Canton(Authors)
    • 2018(Publication Date)
    • CRC Press
      (Publisher)
    1.  AND, OR, and XOR logically combine each bit in the source operand with the corresponding bit in the destination operand. The result does not affect the neighboring bits. 2.  The NOT operator inverts all bits in the destination operand.
    These actions explain the term bitwise operation sometimes used to describe the instructions.
    4.1.1    Logical AND
    The AND instruction performs a bitwise logical AND of two operands. This determines that a bit in the result is set if and only if the corresponding bits are set in both operands. A frequent use of the AND operation is to clear one or more bits without affecting the remaining ones. This action is possible because ANDing with a 0 bit always clears the result bit and ANDing with a 1 bit preserves the original value of the first operand.
    For example, if we have the binary coded decimal number 34 packed into a single byte, we can isolate the four low-order bits as follows:
    The second operand, in this case 0FH, is called a mask. The AND operation preserves the 1-bits in the mask and clears the bits that are 0. Consequently, the mask 00000001B clears the seven high-order bits and preserves the original value of the low-order bit.
    4.1.2    Logical OR
    The OR operation performs the bitwise logical inclusive OR of two operands. After a logical OR, a bit in the result is set if one or both of the corresponding bits in the operands were set. A frequent use for the OR is to selectively set one or more bits. The action takes place because ORing with a 1-bit always sets the result bit, while ORing with a 0-bit preserves the original value in the first operand.
    For example, to set the high-order bit (bit number 7) we can OR with a 1 bit, as follows: The OR operation sets the bits that are 1 in the mask and preserves the bits that are masked 0. 4.1.3    Logical XOR
    The XOR operator performs the bitwise logical exclusive OR of the two operands. Therefore, a bit in the result is set if the corresponding bits in the operands have opposite values. For this reason, XORing a value with itself always generates a zero result since all bits necessarily have the same value. On the other hand, XORing with a 1-bit inverts the value of the other operand, since 0 XOR 1 is 1 and 1 XOR 1 is 0. This toggling action of XORing with a 1 bit generates identical bitwise results as the NOT operation, but by selecting the XOR mask, the programmer can control which bits of the operand are inverted and which are preserved.
  • C Programming For Dummies
    • Dan Gookin(Author)
    • 2020(Publication Date)
    • For Dummies
      (Publisher)
    Chapter 5 introduces the basic math operators: +, –, *, and /. The rest aren’t too heavy-duty to understand — even the oddly named modulo.
  • The C language comparison operators are used for making decisions. Refer to Chapter 8 for a list.
  • Logical operators are also covered in Chapter 8 .
  • The single equal sign (=) is an operator, but not a mathematical operator. It’s the assignment operator, used to stuff a value into a variable.
  • Bitwise operators manipulate individual bits in a value. They’re covered in Chapter 17 .
  • Appendix C lists all the C language operators.
  • TABLE 11-1 C Math Operators
    Operator
    Function
    Example
    + Addition var=a+b
    Subtraction var=a-b
    * Multiplication var=a*b
    / Division var=a/b
    % Modulo var=a%b
    ++ Increment var++
    -- Decrement var--
    + Unary plus +var
    Unary minus -var

    Incrementing and decrementing

    Here’s a handy trick, especially for those loops in your code: the increment and decrement operators. They’re insanely useful.
    To add one to a variable’s value, use ++ , as in
    var++;
    After this statement is executed, the value of variable var is increased (incremented) by 1. It's the same as writing this code:
    var=var+1;
    You’ll find ++ used all over, especially in for loops; for example:
    for(x=0;x<100;x++) This looping statement repeats 100 times. It’s much cleaner than writing the alternative: for(x=0;x<100;x=x+1)
    Exercise 11-1: Code a program that outputs this phrase ten times: “Get off my lawn, you kids!” Use the incrementing operator ++ in the for looping statement.
    Exercise 11-2: Rewrite your answer for Exercise 11-1 using a while loop.
    The ++ operator's opposite is the decrementing operator -- , which is two minus signs. This operator decreases the value of a variable by 1; for example:
    var--; The preceding statement is the same as var=var-1;
    Exercise 11-3:
  • Using LEDs, LCDs and GLCDs in Microcontroller Projects
    • Dogan Ibrahim(Author)
    • 2012(Publication Date)
    • Wiley
      (Publisher)
    The ‘&’ operator performs the bitwise AND of its two operands. Each bit of the first operand is ANDed with the corresponding bit of the second operand. The resulting bit is only 1 if both of the two corresponding bits are 1, otherwise the resulting bit is set to 0. An example is given below:
    In this example, variable z takes the hexadecimal value 0×0060. The bitwise ANDing operation is shown below:
    |
    The ‘|’ operator performs the bitwise OR of its two operands. Each bit of the first operand is Ored with the corresponding bit of the second operand. The resulting bit is 1 if either of the corresponding bits are 1, otherwise the resulting bit is set to 0. An example is given below:
    In this example, variable z takes the hexadecimal value 0×FFF1. The bitwise ORing operation is shown below:
    The ‘^’ operator performs the bitwise Exclusive OR of its two operands. Each bit of the first operand is Exclusive Ored with the corresponding bit of the second operand. The resulting bit is 1 if only one of the corresponding bits is 1, otherwise the resulting bit is set 0. An example is given below:
    In this example, variable z takes the hexadecimal value 0×FF91. The bitwise Exclusive ORing operation is shown below:
    The ‘ ’ operator performs the bitwise complement of its operand. Each bit is complemented, thus a 0 becomes a 1, and a 1 becomes a 0. An example is given below:
    In this example, variable y takes the hexadecimal value 0×0F1F. The bitwise complement operation is shown below:
    The ‘<<’ operator performs shift left. The operand is shifted left by n bits, where n is specified by the programmer. The right-hand side of the variable LSB is filled with zeroes, while bits at the left-hand side MSB are lost. Shifting a variable left by 1 bit is the same as multiplying by 2, but the shift operation is much quicker. An example is given below:
    The actual shift left operation for the above example is shown in Figure 3.4 .
    >>
    Figure 3.4 Shifting left by 2 places
    The ‘>>’ operator performs shift right. The operand is shifted right by n bits, where n is specified by the programmer. The left-hand side of the variable MSB is filled with zeroes, while bits at the right-hand side LSB are lost. Shifting a variable right by 1 bit is the same as dividing by 2, but the shift operation is much quicker. An example is given below:
  • Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.