DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C (http://www.daniweb.com/forums/forum118.html)
-   -   bitwise operations in C (http://www.daniweb.com/forums/thread44538.html)

YoTaMiX May 1st, 2006 1:48 pm
bitwise operations in C
 
1 Attachment(s)
Hello :)

i need to write a program which gets from user number and index
( 0 <= number <= 255 , 0<=index<=7) .
then to add up to the number in bitwise a 1 in the place of the index :
if number is 102 which is 01100110
and index is 4 which is 01110110
and get 118 as a result.

for some reason it doesnt do that ..... i have no idea why , i used OR operation between numbers ..... :rolleyes:

Code added

thanx , Yotam

Dave Sinkula May 1st, 2006 1:57 pm
Re: bitwise operations in C
 
102 (decimal) = 1100110 (binary)
1 left shifted 4 is 10000 (binary)
1100110 (binary)
+ 10000 (binary)
-------
1110110 (binary) = 118 decimal
If I understand you.
#include <stdio.h>

int main(void)
{
  int number = 102, index = 4;
  number += 1 << index;
  printf("number = %d\n", number);
  return 0;
}

/* my output
number = 118
*/

YoTaMiX May 1st, 2006 3:08 pm
Re: bitwise operations in C
 
that code is actually adding 1 in place of index ?

Dave Sinkula May 1st, 2006 3:11 pm
Re: bitwise operations in C
 
Bit shifting and bitwise operations

Bench May 1st, 2006 8:30 pm
Re: bitwise operations in C
 
ch2=pow(2,index + 1);
Why did you add 1 to the index? - 32 (2^5) in binary is 00100000 - The code would give your expected result without that.


All times are GMT -4. The time now is 9:21 pm.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC