Example solution

Dependencies:   mbed

main.cpp

Committer:
eencae
Date:
2017-02-02
Revision:
0:cb82516f2dce

File content as of revision 0:cb82516f2dce:

/* ELEC1620 Lab 2 Task 10

Bit-wise Operators

(c) Dr Craig A. Evans, Feb 2017

*/
#include "mbed.h"

int main()
{
    char a = 34;  // 0010 0010
    char b = 107; // 0110 1011
    printf("a = %i\n",a);
    printf("b = %i\n",b);

    printf("We'll shift a by one place to the left and store in c.\n");
    printf("This is the same as multiplying by 2.\n");
    char c = a << 1;  // 0100 0100 = 64 + 4 = 68
    printf("c = %i\n",c);

    printf("We'll shift b by fives place to the right and store in d.\n");
    printf("This is the same as dividing by 2^5 = 32.\n");
    char d = b >> 5;  // 0000 0011 = 2 + 1 = 3
    printf("d = %i\n",d);
    printf("Remember, these are integers so we lose the decimal places.\n");

    printf("Now we'll set bit 6 of c using the bit-wise OR operation.\n");
    char e = c | (1<<6);  // 0100 0100 | 0100 0000
    printf("It turns out bit 6 is already set and so the value doesn't change.\n");
    printf("e = %i\n",e);

    printf("Finally we'll clear bit 2 of c using the bit-wise AND and NOT operation.\n");
    char f = c & ~(1<<2);  // 0100 0100 & 1111 1011 = 0100 0000
    printf("f = %i\n",f);
}