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

9 Key excerpts on "Bitwise Operators in C"

  • Book cover image for: Programming Microcontrollers in C
    • Ted VanSickle(Author)
    • 2001(Publication Date)
    • Newnes
      (Publisher)
    Bitwise Operators Operators that work on the individual bits within a variable are called bitwise operators. Following is a table of all of these opera-tors: & bitwise AND >> right shift | bitwise Inclusive OR << left shift ^ bitwise Exclusive OR ~ one’s complement The first three bitwise operators are traditional binary operators. These binary operators operate in integer type ( char , int , long , etc.) operands, and the two operands must be of the same type. If a bitwise AND is executed, those locations in the result where both operands have bit values of 1 will have a value of 1. All other locations will be 0. For a bitwise inclusive OR , each bit in the result will be 1 when either or both operand bits are 1. All locations where both operand bits are 0 will be 0. The exclusive OR is similar to an addition with no carry. Whenever the bits in the oper-ands are different, the result bit will be 1. If both operand bits are the same, either both bits 1 or both bits 0, the result will be 0. 29 The right shift operator and the left shift operator are also bi-nary operators. Here the types of the operands need not be the same. The expression x >> 3 causes the variable x to be shifted to the right by three bits prior to its use. Likewise, y << 5 will cause y to be shifted to the left by five bits. In all number sys-tems, a left shift by one digit corresponds to a multiplication by the number base. Similarly, a shift to the right by one digit causes a division by the number base. We are using the binary system in this case, so a shift left by one bit causes the number to be multiplied by two. Unlike most number systems, the binary system (or two’s complement system) allows the sign of the number to be contained in the binary representation of the number itself. These consider-ations lead to two different types of shifts for a system of binary numbers. A shift in which bits vacated by the shift are replaced by zeros is called a logical shift .
  • Book cover image for: 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
  • Book cover image for: You Can Program in C++
    eBook - PDF

    You Can Program in C++

    A Programmer's Introduction

    • Francis Glassborow(Author)
    • 2006(Publication Date)
    • Wiley
      (Publisher)
    This means that the left-hand operand will always be evaluated first and the right-hand one will only be evaluated if necessary. WARNING! Lazy evaluation may lead to unexpected behavior. For example, if the left operand of and evaluates as false , the right operand will not be evaluated (and no side-effects of such possible evaluation will happen). FUNDAMENTAL TYPES, OPERATORS, AND SIMPLE VARIABLES 49 Bitwise C++ provides six bitwise operators, i.e. operators that work on the individual bits of storage: Operator Alternative Meaning token & bitand Sets a bit in the result to 1 if and only if both the corresponding bits in the operands are 1 | bitor Sets a bit in the result to 1 if and only if one or both of the corresponding bits in the operands are 1 ^ xor Sets a bits in the result to 1 if exactly one of the corresponding bits in the operands is 1 << Shifts the bits of the left operand left by the number of places given by the right operand (as an unsigned integer value) >> Shifts the bits of the left operand right by the number of places given by the right operand (as an unsigned integer value) ~ compl Inverts the values of all the bits in the single operand that follows WARNING! Bitwise operators can be applied to any integer type, but applying them to signed integer types is usually a mistake and will frequently result in unexpected behavior. The shift operators are particularly vulnerable to inappropriate use of signed values for the left operand. C++ reuses the shift operators as data-streaming operators when the left operand is some kind of data stream. That is by far the most common usage for the ‘shift’ operators in C++. Think of it as shifting data in and out. The & , | and ^ operators are useful for doing masking operations for such things as graphics manipulations.
  • Book cover image for: Microchip AVR Programming using ATmega Microcontrollers
    • Ivan Volosyak(Author)
    • 2021(Publication Date)
    • Shaker
      (Publisher)
    They are used to develop log- ical and mathematical expressions. There are many different types of operators, such as arithmetic (they were already used in task 5.1), bitwise, logical, relational and assignment operators in the C language. All of them are used very often, but bitwise operators are specifically suitable for bit operations in microcontroller programming. Table 5.3: Arithmetic C Operators Arithmetic Operators Description Example + Adds two operands x = a + b; - Subtracts two operands x = a - b; * Multiplies two operands x = a * b; / Divides two operands x = a / b; % Remainder of a division x = a % b; ++ Increment (increases the value by 1) a++; -- Decrement (decreases the value by 1) b--; The first 4 operators shown in Table 5.3 are addition, subtraction, multiplication, and division. The % operator returns the remainder of a division and is called the modulo operator (see also Q&A 11.9 on page 276). Common Mistake: Division of Integer Variables 1 int number1=250; 2 int number2=200; 3 int result = number1/number2; // Beginners expect 1.25, but the result is 1 When two integer numbers are divided, the result will be an integer. The ++ and -- operators can be used either as prefix (e.g. ++a;) or postfix operators (e.g. a++;). Prefix operators increase/decrease the value by 1 and then use the value of the corresponding variable (important is that this value is used in the further calculations in the same line of code). Postfix operators use the value of the variable first, then increase/decrease it by 1. #include #include #include "lcd.h" int main(){ char lcd _ line[25]; int number1=16; int number2=16; lcd _ init(); lcd _ clear(); sprintf(lcd _ line, "%d, %d, %d", number1++, number1, ++number2); // 16, 17, 17 lcd _ string(lcd _ line); return 0; } 82 5 Basic Microcontroller Programming Since the postfix operator is used in the variable number1, its original value is used (16) and converted into the string.
  • Book cover image for: C++ For Dummies
    No longer available |Learn more
    • 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
  • Book cover image for: Embedded Software
    eBook - PDF
    • Colin Walls(Author)
    • 2005(Publication Date)
    • Newnes
      (Publisher)
    4.5 Bit by Bit This piece is based upon one that I wrote for NewBits in 1992, when I was with Microtec UK. Even today, C programmers find bit fields challenging. (CW) In this article I plan to get down to basics and take a look at the issues and challenges associated with memory in embedded systems. At the lowest level, memory is just lots of bits: numerous logic states represented by 1s and 0s. The grouping of these bits into bytes and words is really quite arbitrary; sometimes it becomes necessary to deal with memory bit by bit or in small groups if bits. I will look at how this is accomplished from the C programmer’s perspective. Bitwise Operators C is generally considered a good language for embedded systems programming for a number of reasons, one of which is its ability to perform bitwise arithmetic. All the pri-mary bit operations are available: inversion (using ~ ) to change 1s to 0s and vice versa; AND (using & ) to test bits; OR (using ⎪ ) to set bits; exclusive OR (using Ÿ ) to all toggle specific bits; shift right and left (using >> and << ) by one or more bits. Using these operators, the programmer can perform any required bit manipulation. However, the notation does not yield very easily readable code. This situation is exacer-bated by the need for the expression of bit patterns in hexadecimal (or octal). C does not have a means of including binary constants. For example, it is not intuitive that the following code: bytevar ⎪ = 0xc0; results in the setting of the top two bits of the 8-bit variable bytevar . Binary Constants There is a way to provide what appear to be binary constants in standard C. All that is necessary is a series of macro definitions in a header file ( bits.h perhaps), like this: #define b00000000 ((unsigned char) 0x00) #define b00000001 ((unsigned char) 0x01) #define b00000010 ((unsigned char) 0x02) ...
  • Book cover image for: Basic Computation and Programming with C
    Left shift (<<) operator is used to shift each bit in the operand to left and right shift (>>) operator is used to shift each bit in the operand to right. Shifting the operand n bit to the left is same as multiplying it by 2 n and shifting the operand n bit to the right is same as dividing (integer division) the number by 2 n . R EVIEW E XERCISES 1. What do you mean by bitwise operation? 2. Explain the operations of bitwise operators &, | and ^. 3. What are the left shift and right shift operators? Give some examples which implement those operators. 4. What is one’s complement operator? 5. What are the precedence and associativity of bitwise shift operators? 6. Using bitwise operator write a program in C to check whether an integer is odd or even. 7. Write a program to count number of 1s in the bit pattern of a given integer using bitwise operator. 8. Write a program to rotate right an unsigned integer n number of times. In each rotation each bit will be shifted one place and also recover the lost bit. 9. Write a program that sets one or more bits while other bits remain unchanged. 10. Write a program that inverts a set of bits while other bits remain unchanged. L EARN BY Q UIZ – Q UESTIONS 1 Which of the following is not a bitwise operator? (1) !! (2) ^ (3) && 2 What will be value of c? int a=5, b=6; int c=a|b; (1) 0 (2) 6 (3) 7 Bitwise Operators 523 3 What will be value of c? int a=5, b=6; int c=a&b; (1) 4 (2) 7 (3) 1 4 What will be value of c? int a=5, b=6; int c=a^b; (1) 3 (2) 6 (3) 0 5 What will be value of a and b after evaluating the expression? int a=5, b=6; a=a^b; b=a^b; a=a^b; (1) a=6, b=5 (2) a=6, b=6 (3) a=5, b=5 6 What will be the value of b? int a=4; b=a<<2; (1) 16 (2) 8 (3) 10 7. What will be the value of b? int a=4,b; b=a>>2; (1) 1 (2) 0 (3) 2 8 What will be the value of b? int a=0xfff0, b; b=~a; (1) 15 (2) 0 (3) 2 9. What will be the value of b? int a=−3, b; b=a>>2; Basic Computation and Programming with C 524 (1) −1 (2) 1 (3) 0 10.
  • Book cover image for: C++ for Financial Mathematics
    We have already met > , < , > =, and < =. Also available is == (two equal signs) which is used to test if two numbers are equal and ! = which is used to test if two numbers are different. Danger! Use two equal signs == to compare numbers not one equal sign. One equal sign is for assignment 2.5.4 Logical operators The result of a comparison operation is a bool representing either true or false . You can then combine bool values using the operators && , || , and ! , which mean and, or, and not, respectively. So, for example, true && false evaluates to false . 2.5.5 Bitwise operators The operators & , | , ^ , ~, << and >> treat integers as simply binary data and perform manipulations on these bits. • ~ is the bit inversion operator. So ~x contains binary representation of x but with all the 1’s and 0’s switched. • << shifts all the bits in a number to the left by a given amount. So x<<3 shifts all the bits 3 steps to the left. • >> shifts all the bits in a number to the right by a given amount. So x>>3 shifts all the bits 3 steps to the right. 30 C++ for Financial Mathematics • & is the bitwise AND operator. The n -th bit of a&b is equal to 1 if the corresponding bit of a is 1 AND the corresponding bit of b is 1. • | is the bitwise OR operator. The n -th bit of a|b is equal to 1 if the corresponding bit of a is 1 OR the corresponding bit of b is 1. • ^ is the bitwise exclusive or operator (XOR). The n -th bit of a^b is equal to 1 if the corresponding bit of a is 1 OR the corresponding bit of b is 1, BUT is 0 IF BOTH ARE 1. These operators will be of no interest to us in this book, but are very useful if you are working with computer graphics. For example, you can use the NOT operator to generate the negative of a black and white image. The only thing you have to remember is that you want to use && to mean “and” and not & . Danger! The operator ^ does not mean raise to a power, it means XOR.
  • Book cover image for: Some Assembly Required
    eBook - PDF

    Some Assembly Required

    Assembly Language Programming with the AVR Microcontroller

    • Timothy S Margush(Author)
    • 2016(Publication Date)
    • CRC Press
      (Publisher)
    The process of setting, clearing, and toggling a bit (or several bits) is commonly accomplished through the use of a logical instruction and a constant value called a bit mask. The bit mask is a string of bits of the same size as the data being manipulated. In the AVR processor, all of these operations apply to bytes, so the bit masks are also a byte. • To set a bit (or multiple bits), create a mask with 1’s in the positions to be set (0’s elsewhere). Perform a logical OR operation. • To clear a bit (or multiple bits), create a mask with 0’s in the positions to be cleared (1’s elsewhere). Perform a logical AND operation. • To toggle (flip) a bit (or multiple bits), create a mask with 1’s in the posi-tions to be flipped (0’s elsewhere). Perform a logical EOR operation. Logical Operations ◾ 281 Masks Masks are often created via expressions in assembly language programs. For example, the mask needed to convert letters to lowercase (set bit five) is the result of the expression 1 << 5 . To clear bit five, you need the com-plement of this, ~(1 << 5 ). The mask to toggle bit five is the same as the one used to set bit five. To create a mask with several bits set, use the bitwise or operator. Thus, the mask 0b01001000 would be written (1 << 6)|(1 << 3) . The comple-ment could be expressed as ~((1 << 6)|(1 << 3)) . Note that these expres-sions are evaluated by the assembler; they are not logical instructions executed by the processor. Another task that can be accomplished using logical instructions is the extraction of a digit value from a digit character. The ASCII codes for the characters “0” through “9” are 0x30 through 0x39. Masking out (clearing) the upper four bits will convert the ASCII code to unsigned 8-bit data. This mask is usually written as 0x0F rather than constructing it using an expression. To convert in the opposite direction (unsigned byte to ASCII), you would simply set bits five and four, as in ori Rd, 0x30 .
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.