[1+1=2]

OneAndOneIs2

« Those who live in glass houses. . .Blogging (and why Linux users should) »

Sat, Jan 27, 2007

[Icon][Icon]Bitwise operators

• Post categories: Omni, Programming

I swear, it takes longer to understand the question that in does the answer for these exercises.

In this case, you have to take 'n' bits from the binary value of 'x', beginning at position 'p'. Then set the rightmost bits of 'y' to those bits.

So if you have:
x = 14 = 001110
y = 13 = 001101
n = 3
p = 5

You want the '001' from x to be put at the end of y, to give 001001, which equals 9. The function I wrote does this, so I call it good. The annoying part was writing the main() function to actually test the setbits() function. So it goes. . .

Follow up:

int setbits(int x, int p, int n, int y)
{
    /* Set the n bits beginning at p to be rightmost and zero all others */
    x = (x >> (p+1-n)) & ~(~0 << n);
    /* Zero the rightmost n bits of y */
    y = y & (~0 << n);
    /* Add the desired n bits of x to the zeroed n bits of y */
    return x+y;
}

3 comments

Alison
Comment from: Alison [Visitor] · http://www.creativehedgehog.com
bitwise operators- do not like...
29/01/07 @ 03:16
oneandoneis2
Comment from: oneandoneis2 [Member] · http://geekblog.oneandoneis2.org/
Me neither. Unfortunately, I can see how useful they can be, so I can't just skip this section and worry about it later. . .
29/01/07 @ 09:24
Rajendra Kumar Uppal
Comment from: Rajendra Kumar Uppal [Visitor]
http://discuss.fogcreek.com/joelonsoftware4/default.asp?cmd=show&ixPost=135960&ixReplies=9
14/11/09 @ 11:49

Leave a comment


Your email address will not be revealed on this site.

Your URL will be displayed.
(Line breaks become <br />)
(Name, email & website)
(Allow users to contact you through a message form (your email will not be revealed.)
This is a captcha-picture. It is used to prevent mass-access by robots.
Please enter the characters from the image above. (case insensitive)
 

[Links][icon] My links

[Icon][Icon] Hmm.. new look for twitter? I hope it gets less "Ick! Change! Put it back!" nonsense than Facebook..
08/02/12

[Icon][Icon] Facebook Syndication Error
11/02/12

[Icon][Icon] I last listened to:
Johann Pachelbel - Canon in D major

[Icon][Icon] Most recent photo:
Submersible houseboat

[Icon][Icon]About Me

[Icon][Icon]About this blog

[Icon][Icon]My LQ profile

[Icon][Icon]My /. profile

[Icon][Icon]My Wishlist

[Icon]MyCommerce

[FSF Associate Member]


February 2012
Mon Tue Wed Thu Fri Sat Sun
 << <   > >>
    1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29        

Search

User tools

XML Feeds

eXTReMe Tracker

Valid XHTML 1.0 Transitional

Valid CSS!

[Valid RSS feed]

free open source blog