please help.function in C

  • sanndra9
  • Born
  • Born
  • sanndra9
  • Posts: 2

Post 3+ Months Ago

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
  • _Leo_
  • Proficient
  • Proficient
  • User avatar
  • Posts: 279
  • Loc: Buenos Aires, Argentina

Post 3+ Months Ago

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 99 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
 
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.