Square of a number using Bitwise
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: Square of a number using Bitwise

  1. #1
    Join Date
    Apr 2007
    Location
    Mars NASA Station
    Posts
    1,436

    Square of a number using Bitwise

    Hello to all expert, i would like to square a number using bit operation since bit twiddling is quite important.


    AFAIK, 33 & 1 will yields 1 to get its least significant digits.

    How to check second or third least digit towards most significant digit ?

    Example:

    2 * 2

    0000 0010
    0000 0010

    The digit of 1 & 1 result 1 so left shift 1 digit but when 3 *2 is totally difference

    0000 0010
    0000 0011
    0000 0110
    Any hints or reference is greatly appreciated by me ?

    Thanks.
    Last edited by Peter_APIIT; March 27th, 2009 at 05:37 AM.
    Thanks for your help.

  2. #2
    Join Date
    Mar 2009
    Posts
    51

    Re: Square of a number using Bitwise

    You can check each bit like this:
    Code:
    bool isBitSet(int val, int place)
    {
    return 0 != (val & (1 << place));
    }
    Code:
    isBitSet(33,0); // will return true because bit #0 is one.
    isBitSet(33,1); // will return false because bit #1 is zero.
    Last edited by Zaccheus@Work; March 27th, 2009 at 10:10 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center