Thread: Function purpose

  1. #1
    Registered User
    Join Date
    Feb 2013
    Posts
    58

    Cool Function purpose

    Hi ,
    Could you please help me understand what the "test" function do ?
    test(15,8) >> gives 16
    test(7,15) >> gives 17

    thanks

    Code:
    #include <stdio.h>
    
    int test(unsigned int n ,unsigned int m);
    
    int main()
    {
    
    unsigned int k;
    
    k=test(15,8);
    printf("k= %d\n",k);  // k=16
    
    return 0;
    }
    
    int test(unsigned int n ,unsigned int m)
    {
    return (n+m -1)& ~ (m-1);
    }

  2. #2
    Registered User
    Join Date
    May 2012
    Posts
    505
    Quote Originally Posted by ilans11il View Post
    Hi ,
    Could you please help me understand what the "test" function do ?
    test(15,8) >> gives 16
    test(7,15) >> gives 17
    It's doing logical and arithmetical operations on the two numbers. I can't see a purpose, but if you plotted a 2 dimensional table in x, y you might see an interesting pattern.
    I'm the author of MiniBasic: How to write a script interpreter and Basic Algorithms
    Visit my website for lots of associated C programming resources.
    https://github.com/MalcolmMcLean


  3. #3
    Registered User
    Join Date
    May 2012
    Posts
    1,066
    If you want to understand bit operations, write down the binary representation of the values and do the operations on paper.

    Bye, Andreas

  4. #4
    Registered User
    Join Date
    Apr 2013
    Posts
    1,658
    Looks like m should be a power of 2. What the function does is round a number up and then mask off the lower bits. So if the call is test(x,8), then you get multples of 8: 0 == x returns 0, 0 < x <= 8 returns 8, 8 < x <= 16 returns 16. If the call is test(y,16), then 0 == y returns 0, 0 < y <= 16 returns 16, 16 < y <= 32 returns 32, ...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 02-04-2012, 03:40 AM
  2. Purpose of a function
    By arun10427 in forum C Programming
    Replies: 5
    Last Post: 09-28-2010, 11:24 AM
  3. what is the purpose of this function..
    By transgalactic2 in forum C Programming
    Replies: 4
    Last Post: 03-25-2009, 02:03 AM
  4. What is the purpose of C?
    By Davez69gto in forum C Programming
    Replies: 9
    Last Post: 01-27-2009, 01:09 PM
  5. What is the purpose of this function argument?
    By dudeomanodude in forum C++ Programming
    Replies: 3
    Last Post: 06-30-2008, 06:59 PM