|
Example:
char a = 0b00000001; char b = a << 1; /* b = 00000010 */ char c = a << 2; /* c = 00000100 */ |
|
Example 1: unsigned type
unsigned char a = 0b00000100; unsigned char b = 0b10000100; char c; c = a >> 1; /* c = 00000010 */ c = b >> 1; /* c = 01000010 */ |
Example 2: signed type
char a = 0b00000100; char b = 0b10000100; char c; c = a >> 1; /* c = 00000010 */ c = b >> 1; /* c = 11000010 */ |
How to run the program:
|
Delete the unsigned keyword, re-compile it and re-run it !!!
|
int main( int argc, char* argv[] ) { char a = 1; /* a = 00000001 (= 1) */ a = a << 1; /* Now: a = 00000010 (= 2) */ printf( "a = %d\n", a ); a = a << 1; /* Now: a = 00000100 (= 4) */ printf( "a = %d\n", a ); a = a >> 1; /* Now: a = 00000010 (= 2) */ printf( "a = %d\n", a ); a = a >> 1; /* Now: a = 00000001 (= 1) */ printf( "a = %d\n", a ); a = a >> 1; /* Now: a = 00000001 (= 0) */ printf( "a = %d\n", a ); } |
How to run the program:
|
Examples:
What is stored in an int variable | Value that is represented --------------------------------------+------------------------------- 00000000 00000000 00000000 00000000 | 0 00000000 00000000 00000000 00000001 | 1 00000000 00000000 00000000 00000010 | 2 00000000 00000000 00000000 00000011 | 3 .... ... |
In other words:
|
|
Pseudo code:
bit position 31 bit position 0 | | v v a = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx (32 bits) ^ | bit position i |
void printBits( int a ) { int i; /* 10987654321098765432109876543210 */ unsigned int mask = 0b10000000000000000000000000000000; for ( i = 31; i >= 0; i-- ) { if ( (a & mask) != 0 ) putchar('1'); else putchar('0'); mask = mask >> 1; /* Shift mask bit to right */ } } |
Note:
|
void printBits( int a ) { int i; /* 10987654321098765432109876543210 */ unsigned int mask = 0b10000000000000000000000000000000; for ( i = 31; i >= 0; i-- ) { if ( (a & mask) != 0 ) putchar('1'); else putchar('0'); mask = mask >> 1; /* Shift mask bit to right */ } } int main( int argc, char* argv[] ) { int a; printf( "a = " ); scanf( "%d", &a ); printf( "a = %d\n", a ); printf( "Binary representation = " ); printBits( a ); /* Call the printBits() function */ putchar('\n'); } |
Remember that: a C program always starts running in the main() function (just like Java)
How to run the program:
|