+ All Categories
Home > Documents > 2 Operators

2 Operators

Date post: 17-May-2017
Category:
Upload: aravind-kara
View: 226 times
Download: 1 times
Share this document with a friend
44
OPERATOR : ‘C’ operators can be classified into a number of categories. They are as follows: 1. Arithmetic operators 2. Relational operators 3. Logical operators 4. Assignment Operators 5. Increment & Decrement operators 6. conditional operators 7. Bit wise operators 8. Sizeof operator 9. Comma Operator 10. Memory addressing operators and other operators 1. Arithmetic Operators Table 5-5. Arithmetic operators Operator Meaning Example Result * Multiplication x * y The product of x and y / Division x / y The quotient of x by y % The modulo operation x % y The remainder of x divided by y + Addition x + y The sum of x and y - Subtraction x - y The difference of x and y + (unary) Positive sign +x The value of x - (unary) Negative sign -x The arithmetic negation of x 2. Relational Operators Table 5-9. Comparative operators Operator Meaning Example Result (1 = true, 0 = false) < Less than x < y 1 if x is less than y, otherwise 0
Transcript
Page 1: 2 Operators

OPERATOR : ‘C’ operators can be classified into a number of categories. They are as follows:

1. Arithmetic operators2. Relational operators3. Logical operators4. Assignment Operators5. Increment & Decrement operators6. conditional operators7. Bit wise operators8. Sizeof operator9. Comma Operator10. Memory addressing operators and other operators

1. Arithmetic Operators

Table 5-5. Arithmetic operatorsOperator Meaning Example Result

* Multiplication x * y The product of x and y/ Division x / y The quotient of x by y% The modulo operation x % y The remainder of x divided by y+ Addition x + y The sum of x and y- Subtraction x - y The difference of x and y+ (unary) Positive sign +x The value of x- (unary) Negative sign -x The arithmetic negation of x

2. Relational Operators Table 5-9. Comparative operators

Operator Meaning Exampl

e Result (1 = true, 0 = false)

< Less than x < y 1 if x is less than y, otherwise 0

<= Less than or equal to x <= y 1 if x is less than or equal to y,

otherwise 0> Greater than x > y 1 if x is greater than y, otherwise 0

>= Greater than or equal to x >= y 1 if x is greater than or equal to y,

otherwise 0== Equal to x == y 1 if x is equal to y, otherwise 0

Page 2: 2 Operators

Table 5-9. Comparative operatorsOperator Meaning Exampl

e Result (1 = true, 0 = false)

!= Not equal to x != y 1 if x is not equal to y, otherwise 0

3. Logical Operators Table 5-10. Logical operators

Operator Meaning Exampl

e Result (1 = true, 0 = false)

&& logical AND x && y 1 if each of the operands x and y is not

equal to zero, otherwise 0

|| logical OR x || y 0 if each of x and y is equal to zero, otherwise 1

! logical NOT !x 1 if x is equal to zero, otherwise 0

Alternate Spellings: The iso646.h Header Fileif (ch != '"' && ch != '\'') charcount++;

this way:

if (ch != '"' and ch != '\'') charcount++;

Table 7.3. Alternative Representations of Logical OperatorsTraditional iso646.h

&& and|| or! not

1. Assignment Operator:

In an assignment operation, the left operand must be a modifiable lvalue; in other words, it must be an expression that designates an object whose value can be changed.

Page 3: 2 Operators

Table 5-7. Assignment operators

Operator Meaning Example Result

= Simple assignment x = y Assign x the value of y.

+= -=*= /= %=&= ^= |=<<= >>=

Compound assignment

x *= y For each binary arithmetic or binary bitwise operator op, x op= y is equivalent to x = x op (y).

Increment & Decrement Operator

Table 5-8. Increment and decrement operatorsOperator Meaning Side effect Value of the expression

Postfix:x++

Prefix:++x

Increment Increases the value of x by one (like x = x + 1).

The value of x++ is the value that x had before it was incremented.The value of ++x is the value that x has after it has been incremented.

Postfix:x--

Prefix:--x

Decrement

Decreases the value of x by one (like x = x - 1).

The value of x-- is the value that x had before it was decremented.The value of --x is the value that x has after it has been decremented.

Conditional OperatorsA ternary operator “ ? : “ is thereExp1? Exp2:exp3;

7. Bitwise operators

Table 5-11. Boolean bitwise operatorsOperator Meaning

Example

Result (for each bit position)(1 = set, 0 = cleared)

& Bitwise AND x & y 1, if 1 in both x and y

Page 4: 2 Operators

Table 5-11. Boolean bitwise operatorsOperator Meaning

Example

Result (for each bit position)(1 = set, 0 = cleared)0, if 0 in x or y, or both

| Bitwise OR x | y 1, if 1 in x or y, or both0, if 0 in both x and y

^ Bitwiseexclusive OR

x ^ y 1, if 1 either in x or in y, but not in both0, if either value in both x and y

~ Bitwise NOT(one's complement )

~x 1, if 0 in x0, if 1 in x

<< left shift integral promotions>> right shift integral promotions

Bitwise AND

AND cond is 1&1=1 all other comb 0 Its used to check wether particular bit is set or notif ((flag & MASK) == MASK) puts("Wow!");

if(7&4)printf(“bit 4 is set “);elsebit 4 is clearyou can use if(7&4) or if(7&4 !=0) as if(7&4) inturn returns 1 or 0 based on 4 th bit set or clear

Turning Bits Off or clearing particular bit to offflags &= ~MASK; or flags= flags&~MASK;7&~4=3//here 4th bit pos cleared

clear the bit in specified pos (if bit num starts from 0 inseted of 1 works)val=val&~(1<<bitnum);

checks the bit is 1 0r 0val=val&1<<bitnum

Bitwise OR Sometimes you might need to turn on particular bits in a value while leaving

the remaining bits unchanged.flags |= MASK;

Seting bit on particular pos

Page 5: 2 Operators

val=val | 1<<bitnum

Ex-OR Toggling Bit

flag ^= MASK;

Swap a and b arounda ^= b; b ^= a; a ^= b;

or equivalently,a ^= b ^= a ^= b;

SET,CLEAR,TOGGLE BITflags |= DIRTY; /* set DIRTY bit */flags &= ~OPEN; /* clear OPEN bit */flags ^= VERBOSE; /* toggle VERBOSE bit */

Return a mask that set the first 1c & (~c + 1) or c & -c //it gives 1st 1 location for sted val i.e c=8-> 8|3->11->11&(~11+1)->1//8(1000) after ored with 3 res is 11(1011) here1st 1 setted location is 1Return a mask that set the first 0~c & (c + 1)//it gives 1st location of zero for seted val i.e c=8-> c=c|3->11-> ~11+(11+1)->4//8(1000) after ord with 3 res is 11(1011) here 1st 0d location is 4

Bit count -Count number of 1int count_one1(int c){ int i; for (i = 0; c; i++)//here c is a cond like if(c) or if(c!=0) c ^= (c & -c); //check note return i;}Note: C&-C gives pos of 1st bit whre 1 is there(like pos 1,2,4,8,16,32...) eg: c=7; (c&-c)->7&-7=1 c^(c&-c)->7^1 here i become 1 c=6-> 6&-6=2 6^2=4; i=2 c=4 -> 4&-4=4 4^4=0 i=3 so nof 1’s here is 3(0111-7)

int count_one2(int c){ int i; for (i = 0; c; i++) c &= (c - 1); return i;} Note: if c=7, 7&6(c&=(c-1))->6 i=1 -> 6&5=4 i=2 -> 4&3=0 i=3 so no of 1’s=3(0111-7)

Page 6: 2 Operators

int count_one3(int c){ int n = 0, i; for (i = 0; i < 32; i++) { if (c & 1) n++; c >>= 1; } return n;}

Note: Here right shift works by moving 1’s to right side by padding zeros on left and &1 check n counts eg: c=1010(10) -> c&1=0,n=0 , 10>>1=0101(5) -> 5&1=1,n=1 , 5>>1=2 -> 2&1=0,n=1, 2>>1=1 -> 1&1=1,n=2 1>>1=0->0&0=0 ,n=2 so total 1’s are 2

write a code to count the no.of 1s in a given 16 bit integer.int num /*Given 16 bit integer*/int count = 0; /*gives total no. of 1's in num*/for(i=0;i<16;i++){if((num>>i) && 1){count++;}}--Note: in single cond itself we can check by right shifting and anding with 1 like above egMost optimal solution would be -int num /* given 16 bit integer */int count = 0; /* total no. of 1's in num */while (num & (num-1)) {count++;num = num & (num-1);}print(++count);}

int bitcount(unsigned char x)

{ int count; for (count=0; x != 0; x>>=1)

if ( x & 01) count++; return count; }

Page 7: 2 Operators

Left rotate a byte by certain bitschar rotate(char c, int i){ i %= 8; return (c << i) | ((unsigned char)c >> (8 - i));}

Left shift: value << n discard the n leftmost bits, and add n zeroes to the right number << n Multiplies number by 2 to the nth power

Right shift: value >> n Two definitions: logical version:

discard the n rightmost bits, and add n zeroes to the left for negative values, the sign bit is the leftmost bit – so

logical right shift has the effect of making the value positive

number >> n Divides number by 2 to the nth power if number is not negative

One diff i have seen in calculator8<<1 (in hex) o/p is 10 (1000(8)<<0001(1))(0 is added on right side of 8 so 0001 0000=10)8<<1 (in dec) o/p is 16 (8* 2^1 =8*2=16) (compiler follow this)

NOTE: Shifting is much faster than actual multiplication (*) or division (/) by 2. So if you want fast multiplications or division by 2 use shifts.

Suppose you have two integer variables, h and l, whose values are between 0 and 15 inclusive, and you want to set r to an 8-bit value whose low-order bits are those of l and whose high-order bits are those of h. The natural way to do this is to write:

r = h<<4 + l;Unfortunately, this is wrong. Addition binds more tightly than shifting, so this example is equivalent tor = h << (4 + l);Here are two ways to get it right:r = (h << 4) + l;r = h << 4 | l;One way to avoid these problems is to parenthesize everything, but expressions with too many parentheses are hard to understand, so it is probably useful to try to remember the precedence levels in C. Unfortunately, there are fifteen of them, so this is not always easy to do. It can be made easier, though, by classifying them into groups.

Page 8: 2 Operators

We can also use the bitwise operators to extract subsets of bits from the middle of an integer. For example, to extract the second-to-last hexadecimal ``digit,'' we could use

(i & 0xf0) >> 4If i was 0x56, we have:I 0 1 0 1 0 1 1 0& 0x56 & 1 1 1 1 0 0 0 0---------------0 1 0 1 0 0 0 0 (0x56&0xF0 = 0x50)and shifting this result right by 4 bits gives us 0 1 0 1, or 5, as we wished (0x50 >>4 =0x5) i.e we get 1st value

int main(){char* cp = "abcdef";printf("%d\n", sizeof(cp));             //pointer to char -> 4

char ca[] = "abcdef";printf("%d\n", sizeof(ca));             //abcdef + '\0" -> 7

char ca2[100] = "abcdef" ;printf("%d\n", sizeof(ca2));           //100

int ia[100];printf("%d\n", sizeof(ia));              //100 * 4 -> 400

Page 9: 2 Operators

char* cp2 = (char*) sizeof(100);       printf("%d\n", sizeof(cp2));              //4     printf("%d\n", sizeof(s1));             //8printf("%d\n", sizeof(s2));             //12      printf("%d\n", sizeof(s3));             //3        printf("%d\n", sizeof(s4));             //12   return 0;}char f() {return 'c';}

sizeof vs strlen#include <stdio.h>#include <string.h>

int main(){    char *m = "abcde";    printf("%d\n", strlen(m));

    char r[] = "abcde";    printf("%d\n", sizeof(r));}Output:56

Memory Addressing OperatorsTable 5-14. Memory addressing operators

Operator Meaning Example Result& Address of &x Pointer to x

* Indirection operator *p The object or function that p

points to[ ] Subscripting x[y] The element with the index y in

Page 10: 2 Operators

Table 5-14. Memory addressing operatorsOperator Meaning Example Result

the array x (or the element with the index x in the array y: the [ ] operator works either way)

. Structure or union member designator

x.y The member named y in the structure or union x

-> Structure or union member designator by reference

p->y The member named y in the structure or union that p points to

Table 5-15. Other operatorsOperator Meaning Example Result( ) Function call log(x) Passes control to the specified

function, with the specified arguments.

(type name) {list}

Compound literal (int [5]){ 1, 2 }

Defines an unnamed object that has the specified type and the values listed.

sizeof Storage size of an object or type, in bytes

sizeof x The number of bytes occupied in memory by x.

(type name)

Explicit type conversion, or "cast"

(short) x The value of x converted to the type specified.

?: Conditional evaluation

x ? y : z The value of y, if x is true (i.e., nonzero); otherwise the value of z.

, Sequential evaluation

x,y Evaluates first x, then y. The result of the expression is the value of y.

Operator Precedence: Category Operator Associativit

yPostfix ( ) [ ] -> . ++ -- Left to right

Unary prefix + - ! ~ ++ -- (type) * & sizeof Right to left

Multiplicative * / % Left to right

Page 11: 2 Operators

Additive + - Left to rightShift << >> Left to rightRelational < <= > >= Left to rightEquality == != Left to rightBitwise AND & Left to rightBitwise XOR ^ Left to rightBitwise OR | Left to rightLogical AND && Left to rightLogical OR || Left to rightConditional ?: Right to left

Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left

Comma , Left to right

C Language Operator PriorityOperators Associativity() [] -> .  left to right! ~ ++ -- + - * (type) sizeof  right to left* / %  left to right+ -  left to right<<  >>  left to right< <= > >=  left to right== !=  left to right&  left to right^  left to right|  left to right&&  left to right||  left to right?:  right to left=  +=  -=  *=  /=  %=  &=  ^=  |=  <<= >>=

right to left

,  left to right

10.What does the modulus operator do?The modulus operator (%) gives the remainder of two divided numbers. For instance, consider the following portion of code:x = 15/7

Page 12: 2 Operators

If x were an integer, the resulting value of x would be 2. However, consider what would happen if you were to apply the modulus operator to the same equation:x = 15%7The result of this expression would be the remainder of 15 divided by 7, or 1. This is to say that 15 divided by 7 is 2 with a remainder of 1.The modulus operator is commonly used to determine whether one number is evenly divisible into another. For instance, if you wanted to print every third letter of the alphabet, you would use the following code:int x;for (x=1; x<=26; x++)if ((x%3) == 0)printf(“%c”, x+64);The preceding example would output the string “cfilorux”, which represents every third letter in the alphabet.

9.What is the difference between ++var and var++?The ++ operator is called the increment operator. When the operator is placed before the variable (++var), the variable is incremented by 1 before it is used in the expression. When the operator is placed after the variable (var++), the expression is evaluated, and then the variable is incremented by 1. The same holds true for the decrement operator (–). When the operator is placed before the variable, you are said to have a prefix operation. When the operator is placed after the variable, you are said to have a postfix operation. For instance, consider the following example of postfix incrementation:int x, y;x = 1;y = (x++ * 5);In this example, postfix incrementation is used, and x is not incremented until after the evaluation of the expression is done. Therefore, y evaluates to 1 times 5, or 5. After the evaluation, x is incremented to 2. Now look at an example using prefix incrementation:int x, y;x = 1;y = (++x * 5);This example is the same as the first one, except that this example uses prefix incrementation rather than postfix. Therefore, x is incremented before the expression is evaluated, making it 2. Hence, y evaluates to 2 times 5, or 10.

Obscure syntax23. C allows some appalling constructs. Is this construct legal, and if so what does this code do?

int a = 5, b = 7, c;c = a+++b;This question is intended to be a lighthearted end to the quiz, as, believe it or not, this is perfectly legal syntax. The question is how does the compiler treat it? Those poor compiler writers actually debated this issue, and came up with the "maximum munch" rule, which stipulates that the compiler should bite off as big (and legal) a chunk as it can. Hence, this code is treated as:c = a++ + b;Thus, after this code is executed, a = 6, b = 7, and c = 12.If you knew the answer, or guessed correctly, well done. If you didn't know the answer then I wouldn't consider this to be a problem. I find the greatest benefit of this question is that it is good for stimulating questions on coding styles, the value of code reviews, and the benefits of using lint.

Page 13: 2 Operators

41.What is the value of sizeof(a) /sizeof(char *) in C code snippet below char *a[4]={“sridhar”,”raghava”,”shashi”,”srikanth”}; explain

Explanation:Here a[4] is an array which holds the address of strings. Strings are character arrays themselves.Memory required to store an address is 4 bits. So memory required to store 4 addresses is equal to 4*4=16 bits.char *; is a pointer variable which stores the address of a char variable.So sizeof(char *) is 4 bits. Therefore sizeof(a) /sizeof(char *) = 16/4 = 4 bytes.

size of a datatype without using sizeofHi allI have a datatype say X and I want to know its size without declaring a variable or pointer of that type and of course without using sizeof operator.Is this possible. I thought of using standard header files which contain size and range of datatypes but that doesn't work with user defined datatype.Any help will be appreciated.Thanx

To my mind, this fits into the category of "how do I add two ints without using ++, += or + ?". It's a waste of time. You can try and avoid the monsters of undefined behaviour by doing something like this.size_t size = (size_t)(1 + ((X*)0));

Note that I don't declare a variable of type or pointer to X.--Well, I am an amateur..but I tried out this problem and I got the right answer without using sizeof. Hope this helps.. I am trying to find the size of an integer.int *a,*s, v=10;

a=&v;

s=a;

a++;

int intsize=(int)a-(int)s;

printf("%d",intsize);

how to know size of int without sizeof [closed]Possible Duplicate:size of a datatype without using sizeofThis is question asked in a C interview I wanted to know what is the correct logic for thisIf you are not having a sizeof operator in C, how will you get to know the size of an int ?

Use an array[*]:int a[2];int sizeof_int = (char*)(a+1) - (char*)(a);

Page 14: 2 Operators

Actually, due to a note in the section on pointer arithmetic, you don't even need an array, because for the purposes of pointer arithmetic an object behaves like an array of size 1, and an off-the-end pointer is legal for an array:int a;int sizeof_int = (char*)((&a)+1) - (char*)(&a);

[*] By which I mean, "a solution to the puzzle posed is to use an array". Don't actually use an array, usesizeof!

Algorithm in C - playing with numbers - number with 3 in units placeI came across this question in an interview. Any number with 3 in its units position has at least one multiple containing all ones. For instance, a multiple of 3 is 111, a multiple of 13 is 111111. Given a number ending in 3, I was asked the best method to find its multiple containing all 1's. Now a straightforward approach is possible, where you do not consider space issues but as the number grows, and sometimes even if it doesn't, an int (or a long int at that!) in C cannot hold that multiple. What is the optimal way to implement such an algorithm in C?--The multiple of 23 is 1111111111111111111111#include <stdio.h>

intmain () {        unsigned int ones = 1;        double result, by = 23, dividend = 1;        while (dividend) {            result = dividend / by;                if (result < 1) {                    dividend = dividend * 10 + 1;                        ++ones;                } else {                    dividend -= by * (int)result;                }        }        while (ones--) {            printf("1");        }        printf("\n");    return 0;}

--Write a function to print the binary value of the number passed to it, and function should not use any variables other than the parameter passed to it.

Answer : We need to use recursion for this, and here is my version of the C code for the same

Page 15: 2 Operators

#include <stdio.h>

void printBinary(int k){ if(k != 0) { printBinary(k/2); } printf("%d", k%2);}void main(void){ int k = 4561; printBinary(k);}

--Set , Get , Clear ,Toggle , Display Bits ? 

// Display Every bits in a int number void displayBits(int data){ int dataSize = 1<<sizeof(data); int count = 0; for (count = dataSize;count >= 0; count--) { printf("%d",(testBit(data,count))); }}// test a bit if it is zero or one int8_t testBit(int8_t value,int whichBit){ int mask = 1 << whichBit; if (value&mask) { return TRUE; } else return FALSE;}

// Set a bit to one int8_t setBit(int8_t result, int whichBit){ return (result |= (1<<whichBit));}

// toggle a bit int8_t toggleBit(int8_t result, int whichBit){

Page 16: 2 Operators

return (result ^= (1<<whichBit));}

/* Clear a bit to zero */int8_t clearBit(int8_t result, int whichBit){ return (result &=~ (1<<whichBit));}

--Convert number 2 --> 37 without using any other operator but bitwise ?  

Answer: int x = 2; printf("X before :%d\n",x); x = (x<<x<<x) | (x<<x<<x) | x<<!!x | !!x ; printf("X After :%d\n",x);

--Q: For bit manipulation  C  has some operators.Write a function rotate(m,n)       that returns the value of the integer  m rotated to the right by n positions.  A:#include<stdio.h> main() {  int shift(int,int);  int m = 33;  int n = 5;  printf("Rotating of %d to the right %d times results in %d number!\n",m,n,shift(m,n));  } int shift(int a,int b) {   int c=a;   int i=0;  /* bit counter */   int mask=1;     while(c!=0)  /* looking for the most significant bit and set it =1 */    {     c=c>>1; 

Page 17: 2 Operators

    i++;     }   mask=mask<<(i-1);   while(b-->0)  /* rotate b times */   {       if (a & 1)        {         a =a>>1;         a = a | mask;         }     else a =a>>1;    }  return a; }--

--write a c code to reverse the bits in a uint8 type variable.unsigned intreverse(register unsigned int x){x = (((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1));x = (((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2));x = (((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4));x = (((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8));return((x >> 16) | (x << 16));}--unsigned char reverse(unsigned char x){ unsigned char h = 0; int i = 0;

for(h = i = 0; i < sizeof(x); i++) { h = (h << 1) | (x & 1); x >>= 1; }

return h;}--unsigned intreverse_8bit(register unsigned int x){x = (((x & 0xaa) >> 1) | ((x & 0x55) << 1));

Page 18: 2 Operators

x = (((x & 0xccc) >> 2) | ((x & 0x333) << 2));x = (((x & 0xf0) >> 4) | ((x & 0x0f) << 4));return x;}}--void reverse_bit(unsigned char num){unsigned int i,rev_bit=0;printf("Enter a Number \n");scanf("%x",&num);for(i=0;i<(sizeof(num)*8);i++){rev_bit|=((num ^ (0x1<<i)) &(0x1<<i));}printf("Total=0x%x\n",rev_bit);}--char ReverseUint8 ( char x){char y = 0;int i; unsigned char var = 0x01;unsigned char var_f = 0x80;for ( i = 0 ; i < 8 ; i++){if ( x & var ){y |= var_f; }

var = var<<1;var_f = var_f>>1;

// printf("\n x = %d , y = %d ",x, y);

}

return y;}--45.Which one is equivalent to multiplying an unsigned int by 2,left shifting by 1 or right

shifting by 1?Left shifting of an unsigned integer is equivalent to multiplying an unsigned int by 2.Eg1: 14<<1;consider a number 14—–00001110 (8+4+2)is its binary equivalentleft shift it by 1————–00011100(16+8+4) which is 28.Eg2: 1<<1;consider the number as 1—00000001(0+0+1).left shift that by 1————00000010(0+2+0) which is 2.left shift by 1 bit of a number=2*number

Page 19: 2 Operators

left shift by 1 bit of 2*number=2*2*numberleft shift by n bits of number=(2^n)*numberProgram:Program to illustrate left shift and right shift operations.#include<stdio.h>int main(void){ int x=10,y=10; printf("left shift of 10 is %d \n",x<<1); printf("right shift of 10 is %d \n",y>>1); return 0;}

Download codeOutput:left shift of 10 is 20right shift of 10 is 5Explanation:Left shift (by 1 position) multiplies a number by two. Right shift divides a number by 2.

--

1. Write a program to check whether a given number is a palindromic number.If a number, which when read in both forward and backward way is same, then such a number is called a palindrome number.Program:#include <stdio.h>int main() { int n, n1, rev = 0, rem; printf("Enter any number: \n"); scanf("%d", &n); n1 = n; /* logic */ while (n > 0){ rem = n % 10; rev = rev * 10 + rem; n = n / 10; } if (n1 == rev){ printf("Given number is a palindromic number"); } else{ printf("Given number is not a palindromic number"); } return 0;}

Output:Enter any number: 121Given number is a palindromeExplanation with an example:consider a number n=121, reverse=0, remainder; number=121 now the while loop is executed /* the condition (n>0) is satisfied */

Page 20: 2 Operators

/* calculate remainder */ remainder of 121 divided by 10=(121%10)=1;

now reverse=(reverse*10)+remainder =(0*10)+1 /* we have initialized reverse=0 */ =1

number=number/10 =121/10 =12

now the number is 12, greater than 0. The above process is repeated for number=12. remainder=12%10=2; reverse=(1*10)+2=12; number=12/10=1;

now the number is 1, greater than 0. The above process is repeated for number=1. remainder=1%10=1; reverse=(12*10)+1=121; number=1/10 /* the condition n>0 is not satisfied,control leaves the while loop */

Program stops here. The given number=121 equals the reverse of the number. Thus the given number is a palindrome number.

17.Which bitwise operator is suitable for checking whether a particular bit is ON or OFF?Bitwise AND operator.Example: Suppose in byte that has a value 10101101 . We wish to check whether bit number 3 is ON (1) or OFF (0) . Since we want to check the bit number 3, the second operand for AND operation we choose is binary 00001000, which is equal to 8 in decimal.Explanation:ANDing operation :

10101101 original bit pattern 00001000 AND mask --------- 00001000 resulting bit pattern ---------

The resulting value we get in this case is 8, i.e. the value of the second operand. The result turned out to be a 8 since the third bit of operand was ON. Had it been OFF, the bit number 3 in the resulting bit pattern would have evaluated to 0 and complete bit pattern would have been 00000000. Thus depending upon the bit number to be checked in the first operand we decide the second operand, and on ANDing these two operands the result decides whether the bit was ON or OFF.

--17.Which bit wise operator is suitable for turning OFF a particular bit in a number?

Bitwise AND operator (&), one’s complement operator(~)Example: To unset the 4th bit of byte_data or to turn off a particular bit in a number.Explanation:Consider,char byte_data= 0b00010111;byte_data= (byte_data)&(~(1<<4));

Page 21: 2 Operators

1 can be represented in binary as 0b00000001 = (1<<4)

<< is a left bit shift operator,it shifts the bit 1 by 4 places towards left.

(1<<4) becomes 0b00010000

And ~ is the one's complement operator in C language.So ~(1<<4) = complement of 0b00010000 = 0b11101111

Replacing value of byte_data and ~(1<<4) in (byte_data)&(~(1<<4));we get (0b00010111) & (0b11101111)

Perform AND operation to below bytes. 00010111 11101111 ----------- 00000111 -----------

Thus the 4th bit is unset.

--Find binary of a NumberWrite a function to print the binary value of the number passed to it, and function should not use any variables other than the parameter passed to it.

Answer : We need to use recursion for this, and here is my version of the C code for the same

#include <stdio.h>

void printBinary(int k){ if(k != 0) { printBinary(k/2); } printf("%d", k%2);}void main(void){ int k = 4561; printBinary(k);}

Reversing two bits at a time in an arrayI am new to bit manipulation. My friend recently asked me this in an interview. Given an array of bytes Eg: 1000100101010101 | 001010011100 We need to flip it two bits at a time horizontally inplace. So the new array should be: 1000 | 0101 and so on.

Page 22: 2 Operators

and so on. I think we start from the middle (marked by | here) and continue our way outwards taking two bits at a time. I know how to reverse single bits in a number at a time like this:unsigned int reverse(unsigned int num){    unsigned int  x = sizeof(num) * 8;    unsigned int reverse_num = 0, i, temp;

    for (i = 0; i < x; i++)    {        temp = (num & (1 << i));        if(temp)            reverse_num |= (1 << ((x - 1) - i));    }

    return reverse_num;}

But I wonder how can we reverse two bits efficiently inplace. Thanks in advance.--I'd just do a whole byte (or more) at once:output = (input & 0x55) << 1;output |= (input & 0xAA) >> 1;--Swapping first and last digit in an integer using bitwise operator [closed]I have been asked in an interview to swap the last and first digit in an integer using bitwise operators. Tried a lot but I could not find the solution. How can I do this?Use int digits = log10(x) to get the number of digits.Use int first = x / pow(10,digits) to get the first digit.Use int last = x % 10 to get the last digit.Put it all together and you haveint swapped = x + (last - first) * pow(10,digits) + (first - last)--#include <stdio.h>#include <string.h>

int main(){    int n = 123456789;

    char buf[100];    int r = snprintf(buf, sizeof(buf), "%d", n);    char t = buf[0];    buf[0] = buf[r-1];    buf[r-1] = t;    int swap;    sscanf(buf, "%d", &swap);

    printf("n = %d,  swap = %d\n", n, swap);

Page 23: 2 Operators

    return 0;}--Test Your C Skills

                     

 1) Shift the bits as illustrated above In the picture

     unsigned char A = 171;     unsigned char B = 223;     unsigned char C = 0;

     //Solution     C = (A >> 3) | ((B >> 5) << 5);

     printf("A = %d , B = %d , C = %d ",A,B,C)

How to add two numbers without using ++ or + or another arithmetic operatorHow do I add two numbers without using ++ or + or any other arithmetic operator?It was a question asked a long time ago in some campus interview. Anyway, today someone asked a question regarding some bit-manipulations, and in answers a beautiful quide Stanford bit twiddling was referred. I spend some time studying it and thought that there actually might be an answer to the question. I don't know, I could not find one. Does an answer exist?

This is something I have written a while ago for fun. It uses a two's complement representation and implements addition using repeated shifts with a carry bit, implementing other operators mostly in terms of addition.

Page 24: 2 Operators

#include <stdlib.h> /* atoi() */#include <stdio.h>  /* (f)printf */#include <assert.h> /* assert() */

int add(int x, int y) {    int carry = 0;    int result = 0;    int i;

    for(i = 0; i < 32; ++i) {        int a = (x >> i) & 1;        int b = (y >> i) & 1;        result |= ((a ^ b) ^ carry) << i;        carry = (a & b) | (b & carry) | (carry & a);    }

    return result;}

int negate(int x) {    return add(~x, 1);}

int subtract(int x, int y) {    return add(x, negate(y));}

int is_even(int n) {    return !(n & 1);}

int divide_by_two(int n) {    return n >> 1;}

int multiply_by_two(int n) {    return n << 1;}

int multiply(int x, int y) {    int result = 0;

    if(x < 0 && y < 0) {        return multiply(negate(x), negate(y));    }

    if(x >= 0 && y < 0) {        return multiply(y, x);    }

    while(y > 0) {        if(is_even(y)) {

Page 25: 2 Operators

            x = multiply_by_two(x);            y = divide_by_two(y);        } else {            result = add(result, x);            y = add(y, -1);        }    }

    return result;}

int main(int argc, char **argv) {    int from = -100, to = 100;    int i, j;

    for(i = from; i <= to; ++i) {        assert(0 - i == negate(i));        assert(((i % 2) == 0) == is_even(i));        assert(i * 2 == multiply_by_two(i));        if(is_even(i)) {            assert(i / 2 == divide_by_two(i));        }    }

    for(i = from; i <= to; ++i) {        for(j = from; j <= to; ++j) {            assert(i + j == add(i, j));            assert(i - j == subtract(i, j));            assert(i * j == multiply(i, j));        }    }

    return 0;}--Or, rather than Jason's bitwise approach, you can calculate many bits in parallel - this should run much faster with large numbers. In each step figure out the carry part and the part that is sum. You attempt to add the carry to the sum, which could cause carry again - hence the loop.>>> def add(a, b):    while a != 0:        #      v carry portion| v sum portion        a, b = ((a & b) << 1),  (a ^ b)        print b, a    return b

when you add 1 and 3, both numbers have the 1 bit set, so the sum of that 1+1 carries. The next step you add 2 to 2 and that carries into the correct sum four. That causes an exit>>> add(1,3)2 24 0

Page 26: 2 Operators

4

Or a more complex example>>> add(45, 291)66 2704 3328 32816 320336

Edit: For it to work easily on signed numbers you need to introduce an upper limit on a and b>>> def add(a, b):    while a != 0:        #      v carry portion| v sum portion        a, b = ((a & b) << 1),  (a ^ b)        a &= 0xFFFFFFFF        b &= 0xFFFFFFFF        print b, a    return b

Try it onadd(-1, 1)

to see a single bit carry up through the entire range and overflow over 32 iterations4294967294 24294967292 44294967288 8...4294901760 65536...2147483648 21474836480 00L--int Add(int a, int b){    while (b)    {        int carry = a & b;        a = a ^ b;        b = carry << 1;    }    return a;}--How do you set, clear and toggle a single bit in C?Setting a bitUse the bitwise OR operator (|) to set a bit.

Page 27: 2 Operators

 number |= 1 << x;

That will set bit x.Clearing a bitUse the bitwise AND operator (&) to clear a bit. number &= ~(1 << x);

That will clear bit x. You must invert the bit string with the bitwise NOT operator (~), then AND it.Toggling a bitThe XOR operator (^) can be used to toggle a bit. number ^= 1 << x;

That will toggle bit x.Checking a bitYou didn't ask for this but I might as well add it.To check a bit, AND it with the bit you want to check: bit = number & (1 << x);

That will put the value of bit x into the variable bit.--The other option is to use bit fields:struct bits {    unsigned int a:1;    unsigned int b:1;    unsigned int c:1;};

struct bits mybits;

defines a 3-bit field (actually, it's three 1-bit felds). Bit operations now become a bit (haha) simpler:To set or clear a bit:mybits.b = 1;mybits.c = 0;

To toggle a bit:mybits.a = !mybits.a;mybits.b = ~mybits.b;mybits.c ^= 1;  /* all work */

Checking a bit:if (mybits.c)

This only works with bits in fixed positions. Otherwise you have to resort to the bit-twiddling techniques described in previous posts.but bitfield usage is bad idea lot of prob’s--It is sometimes worth using an enum to name the bits:enum ThingFlags = {  ThingMask  = 0x0000,  ThingFlag0 = 1 << 0,  ThingFlag1 = 1 << 1,

Page 28: 2 Operators

  ThingError = 1 << 8,}

Then use the names later on. I.e. writethingstate |= ThingFlag1;thingstate &= ~ThingFlag0;if (thing | ThingError) {...}

to set, clear and test. This way you hide the magic numbers from the rest of your code.Other than that I endorse Jeremy's solution.-- use macros defined in a header file to handle bit set and clear:/* a=target variable, b=bit number to act upon 0-n */#define BIT_SET(a,b) ((a) |= (1<<(b)))#define BIT_CLEAR(a,b) ((a) &= ~(1<<(b)))#define BIT_FLIP(a,b) ((a) ^= (1<<(b)))#define BIT_CHECK(a,b) ((a) & (1<<(b)))

/* x=target variable, y=mask */#define BITMASK_SET(x,y) ((x) |= (y))#define BITMASK_CLEAR(x,y) ((x) &= (~(y)))#define BITMASK_FLIP(x,y) ((x) ^= (y))#define BITMASK_CHECK(x,y) ((x) & (y))--How to set, clear ,toggle and check a single bit in C?As being an embedded software engineer i would really suggest you this tricks. ..!  In many  application you need to deal with this bit wise operation. Sometimes you know this all stuff very well but still some time it takes  time to construct this logic or some time you got some mistakes in it. so i suggest you to paste this on your desk until you paste this in your mind..!To set a bitUse the bitwise OR operator (|) to set a bit. number |= 1 << x; That will set bit x.To clear a bitUse the bitwise AND operator (&) to clear a bit. number &= ~(1 << x); That will clear bit x. You must invert the bit string with the bitwise NOT operator (~), then AND it.To toggle a bitThe XOR operator (^) can be used to toggle a bit. number ^= 1 << x; That will toggle bit x.To check state of a bitTo check a bit, AND it with the bit you want to check: bit = number & (1 << x); That will put the value of bit x into the variable bit. NOTE : here x is the position of bit starting from 0 to LSB.--

Page 29: 2 Operators

How to perform rotate shift in CI have a question as described: how to perform rotate shift in C without embedded assembly. To be more concrete, how to rotate shift a 32-bit int.I'm now solving this problem with the help of type long long int, but I think it a little bit ugly and wanna know whether there is a more elegant method.Kind regards.

From Wikipedia:unsigned int _rotl(unsigned int value, int shift) {    if ((shift &= 31) == 0)      return value;    return (value << shift) | (value >> (32 - shift));}

unsigned int _rotr(unsigned int value, int shift) {    if ((shift &= 31) == 0)      return value;    return (value >> shift) | (value << (32 - shift));}

--How to swap two var.s without using third variable?int a,b;a=a^b;b=a^b;a=a^b;printf (”%d \n  %d\n”, a,b);

--3.count no. of 1 ’s in decimal no?int count (unsigned x){int b;for (b=0; x!=0; x>>=1){if (x&01)b++;}return b;}

--

Multiply by 7 in efficient wayI recently encountered the following interview question:How can you multiply a number by 7 in an efficient and optimized way?I know that I can multiply by 8 (or left-shift by three bits) and then subtract the original value:num = (num << 3) - num;

but are there any other solutions.

--To get a multiple of 7 in an efficient way:

Page 30: 2 Operators

7

7 is a multiple of 7. That answers the question you asked, but I'm sure it doesn't answer the question you mean to ask.EDIT: The above is based on the question's original title,which I've just corrected.To multiply by 7 efficiently, just write, for example:x * 7

and invoke your compiler with optimization. Let the compiler figure out whether a single MUL instruction or something like (x<<3) - x is more efficient for the current machine.There's yet another implicit question here: what answer was the interviewer looking for? I hope that "let the compiler worry about it" would be an acceptable answer. (x<<3) - x is probably the most obvious micro-optimization -- but it can yield incorrect answers if x<<3 overflows, and depending on the system it might be slower than a MUL instruction.(If I were the interviewer, I'd be more impressed by a good explanation and understanding of the issues than by any specific answer.)EDITOn further thought, the kinds of micro-optimizations that have been discussed here might be useful if you know more about the possible values of x than the compiler does. If you know, because of the nature of your program's logic, that x will always be in the range 0..10, then a lookup table could easily be faster than a multiply operation. Or if you know that x is in that range 99% of the time, a lookup table with a fallback to an actual multiplication might be just the thing.But if the compiler's analysis of your program flow doesn't allow it to prove that x is always in that range, then it can't perform this kind of optimization.But such circumstances are very rare. And when your code runs in a new environment where x can be 11 (perhaps it's running on a device with a larger display), kaboom. And the performance improvement very likely wasn't significant in the first place.There are times when micro-optimization is appropriate, but there is a substantial cost in development and testing time. Do it only if actual measurements indicate that it's worth it.--For a limited range, you can use a lookup table:static unsigned int mult7[] = {0, 7, 14, 21, ...};unsigned int three = 3;unsigned int twenty_one = mult7[three];

This may sound silly (and it probably is for this specific case) but it's often handy for things where there is a real cost to calculation. I'm just not certain that multiplying by seven counts as one of those cases.For a start, multiplying x by 7 (or shifting x three bits left then subtracting x) is an operation that can be done entirely inside the CPU. With a table lookup, you might see a multiply-by-four (shift two bits left) followed by an add to get the right address, but then you have to access memory to do the actual lookup - even with caching and all the other wondrous tricks current CPUs are capable of, that's probably going to slow things down.There's also a good chance that your compiler will already know all the tricks about how to multiply fast. If your seven is a constant (or const int or equivalent), the compiler will probably already have chosen the fastest way and there's a good chance the compiler writers know a lot more about this sort of stuff than mere mortals :-) (a)

Page 31: 2 Operators

But for cases where the calculation cost is relatively high, computing the values once and embedding them in your code as a lookup table is one of the standard optimisation strategies (trade off time for space).

(a) Examine the following code:#include <stdio.h>

static int mult7 (int num) {    return num * 7;}

int main (int argc, char *argv[]) {    printf ("%d\n", mult7 (atoi (argv[1])));    return 0;}

With normal compilation by gcc, mult7 comes out as the shift left three and subtract trick:_mult7:    pushl   %ebp             ; stack frame setup.    movl    %esp, %ebp    movl    8(%ebp), %edx    ; get value to edx    movl    %edx, %eax       ;    and eax.    sall    $3, %eax         ; eax <- eax * 8.    subl    %edx, %eax       ; eax <- eax - edx.    popl    %ebp             ; stack frame teardown and return.    ret

At -O3 (what I like to call the insane optimisation level), the whole thing is inlined into main with:call    _atoimovl    $LC0, (%esp)

leal    0(,%eax,8), %edx     ; these two are the relevant instructions.subl    %eax, %edx

movl    %edx, 4(%esp)call    _printf

Note that this inlining action is only possible due to the static nature of the function - if it were visible to the linker, it would have to be maintained as a separate function in case another object file needed to call it.If you take off the static, it does indeed keep it non-inlined with all the stack frame setup and teardown but it at least still uses the (presumably) more efficient trick mentioned below. You can get rid of the stack frame code in gcc if you use -fomit-frame-pointer provided this doesn't adversely affect the code but this is starting to delve into the dark side a little :-)This trick is to use the LEA instruction to set edx to eax * 8 then subtracts eax from that. Same theory as the sall/subl at normal optimisation, just slightly different mechanics.Bottom line, trust your compiler. If you want to multiply num by 7, use the following:num *= 7;

Page 32: 2 Operators

The chances are that whatever improvement you get from such an attempted micro-optimisation, you could get a far better improvement by looking at the macro level (algorithm and data structure selection and so forth).--The way I'd do it would be something likenum = (num << 3) - num;

ie. 2^3 = 8, then subtract the number being multiplied to get a multiple of 7.I just compiled the following code with gcc:int mul(int num){   return num * 7;}

and this is a gdb dump of what it compiled to:Dump of assembler code for function mul:   0x00000000004004c4 <+0>:    push   rbp   0x00000000004004c5 <+1>:    mov    rbp,rsp   0x00000000004004c8 <+4>:    mov    DWORD PTR [rbp-0x4],0xa   0x00000000004004cf <+11>:   mov    edx,DWORD PTR [rbp-0x4]   0x00000000004004d2 <+14>:   mov    eax,edx   0x00000000004004d4 <+16>:   shl    eax,0x3   0x00000000004004d7 <+19>:   sub    eax,edx   0x00000000004004d9 <+21>:   mov    DWORD PTR [rbp-0x4],eax   0x00000000004004dc <+24>:   pop    rbp   0x00000000004004dd <+25>:   ret    End of assembler dump.

So seems for my machine shifting left 3 times and then subtracting the number being multiplied is what gcc believes may be optimal.EDIT: Turns out with an optimisation level of at least 1 (-O1), gcc uses the lea trick:Dump of assembler code for function mul:   0x00000000004004e0 <+0>: lea    eax,[rdi*8+0x0]   0x00000000004004e7 <+7>: sub    eax,edi   0x00000000004004e9 <+9>: ret    End of assembler dump.--Write a C code which returns the position of the first bit set.fot eg. for number 104(1101000) output will be 4.

You need to right shift the number untill the number becomes zero and count the number of times right shifted, then you subtract it from the size of an interger (32 bit on a 32 bit machine), you will get the answer. Here is the code for your reference.

int fbs(unsigned int num){ int pos = -1; while(num!=0) { num <<= 1; pos++;

Page 33: 2 Operators

} return 32 - pos;}

16) Bit manipulation : Embedded systems always require the user to manipulate bits in registers or variables. Given an integer variable a, write two code fragments. The first should set bit 3 of a. The second should clear bit 3 of a. In both cases, the remaining bits should be unmodified. These are the three basic responses to this question: 

1. No idea. The interviewee cannot have done any embedded systems work 

2. Use bit fields. Bit fields are right up there with trigraphs as the most brain-dead portion of C. Bit fields are inherently non-portable across compilers, and as such guarantee that your code is not reusable. The moral: never let a non-embedded person anywhere near a real piece of hardware 

3. Use #defines and bit masks. This is a highly portable method and is the one that should be used. 

My optimal solution to this problem would be:  #define BIT3 (0x1 << 3)static int a; void set_bit3(void) {    a |= BIT3;} void clear_bit3(void) {    a &= ~BIT3;} Some people prefer to define a mask together with manifest constants for the set and clear values. This is also acceptable. The element that I'm looking for is the use of manifest constants, together with the |= and &= ~ constructs 

17. Which bitwise operator is suitable for checking whether a particular bit is ON or OFF?Bitwise AND operator.Example: Suppose in byte that has a value 10101101 . We wish to check whether bit number 3 is ON (1) or OFF (0) . Since we want to check the bit number 3, the second operand for AND operation we choose is binary 00001000, which is equal to 8 in decimal.Explanation:ANDing operation :

10101101 original bit pattern

Page 34: 2 Operators

00001000 AND mask --------- 00001000 resulting bit pattern ---------The resulting value we get in this case is 8, i.e. the value of the second operand. The result turned out to be a 8 since the third bit of operand was ON. Had it been OFF, the bit number 3 in the resulting bit pattern would have evaluated to 0 and complete bit pattern would have been 00000000. Thus depending upon the bit number to be checked in the first operand we decide the second operand, and on ANDing these two operands the result decides whether the bit was ON or OFF.Back to top

18. Which bit wise operator is suitable for turning OFF a particular bit in a number?Bitwise AND operator (&), one’s complement operator(~)Example: To unset the 4th bit of byte_data or to turn off a particular bit in a number.Explanation:Consider,char byte_data= 0b00010111;byte_data= (byte_data)&(~(1<<4));1 can be represented in binary as 0b00000001 = (1<<4)

<< is a left bit shift operator,it shifts the bit 1 by 4 places towards left.

(1<<4) becomes 0b00010000

And ~ is the one's complement operator in C language.So ~(1<<4) = complement of 0b00010000 = 0b11101111

Replacing value of byte_data and ~(1<<4) in (byte_data)&(~(1<<4));we get (0b00010111) & (0b11101111)

Perform AND operation to below bytes. 00010111 11101111 ----------- 00000111 -----------

Thus the 4th bit is unset.

)Given two integers A and B determine how many bits required to convert A to B

Page 35: 2 Operators

Answer :/*Write a functon bitSwapReqd(int A,int B)*/// Straight method(some what not efficient)#define BYTE 8#ifndef TRUE#define TRUE 1#endif#ifndef FALSE#define FALSE (!TRUE)#endifint bitSwapReqd(int A,int B){ int BitsinInt = sizeof(int) * BYTE; int count ; int countRqd = 0; short intA,intB; for (count = 1; count <= BitsinInt; count++) { intA = testBit(A,count); intB = testBit(B,count); /*printf(" intA = %d \n", intA); printf(" intb = %d \n", intB);*/ if(intA != intB) { countRqd++; } } return countRqd;}//Mehtod2 (More efficient)int bitSwapReqd2(int A,int B){ int BitsinInt = sizeof(int) * BYTE; int count,intA = 0 ; int countRqd = 0; int out = A ^ B; //Xor operation done here for (count = 1; count <= BitsinInt; count++) { intA = testBit(out,count); if(intA) { countRqd++; } } return countRqd;

Page 36: 2 Operators

}/* test a bit if it is zero or one */int testBit(int value,int whichBit){ int mask = 1<<whichBit; if (value&mask) { return TRUE; } else return FALSE;}

7)Without using /,% and * operators. write a function to divide a number by 3.itoa() function is available

Answer :

int divisionWithoutArithOprts2(int number){    do

    {        number = number >> 3;    }    while(number >= 0);    return number;}

Write a function which takes an integer value as an argument and return its mod 16 value without using these (%,+,_,/) arithmetic operations

int mod16(int a){ return a>>4;}

The 4 bits left shift will give mod 16.


Recommended