please help.function in C

  • sanndra9
  • Born
  • Born
  • No Avatar
  • Joined: Mar 28, 2004
  • Posts: 2
  • Status: Offline

Post March 28th, 2004, 9:08 am

Please help.I have to write a function in C language.
Here it is.Function must return integer number in which bits from position m to position n are set to 1.
For example input number is 17,and bits on his position five to ten (counting from left ) have value 0 but they have to be changed into value 1,so the number that the function is now returning is 1937.

17 is 0000000000010001 (if size of integer is 2B)
Bold elements are positions between which bits are set to one:
0000011110010001 and now that number is 1937.
I hope it is clear.Thanks.Sanndra
  • Anonymous
  • Bot
  • No Avatar
  • Joined: 25 Feb 2008
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post March 28th, 2004, 9:08 am

  • _Leo_
  • Proficient
  • Proficient
  • User avatar
  • Joined: Feb 17, 2004
  • Posts: 279
  • Loc: Buenos Aires, Argentina
  • Status: Offline

Post March 28th, 2004, 11:46 am

Easy:

Code: [ Select ]
int fill(int ls, int ms, int number) {

 int mask = 0;

 for(int i=ls; i<=ms; i++) {

  mask |= (int)pow(2, i);
 }

 return(number | mask);
}
  1. int fill(int ls, int ms, int number) {
  2.  int mask = 0;
  3.  for(int i=ls; i<=ms; i++) {
  4.   mask |= (int)pow(2, i);
  5.  }
  6.  return(number | mask);
  7. }


ls : less significant bit to start raising
ms : most significant bit to stop
number : number to modify

It's working ok, you have to include <math.h> for using pow()

Post Information

  • Total Posts in this topic: 2 posts
  • Users browsing this forum: No registered users and 114 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
 

© 2011 Unmelted, LLC. Ozzu® is a registered trademark of Unmelted, LLC.