Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / Languages / C# / July 2007

Tip: Looking for answers? Try searching our database.

Set/Unset Bits Operation

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
O.B. - 06 Jul 2007 17:07 GMT
I've written a small operation that sets/unsets bits within an
unsigned integer.  Is there a better way to do this?

static uint setBits(uint original, uint newValue, uint offset, unint
mask)
{
   return ((original >> offset) & (~mask) | newValue) << offset;
}

Example:

uint test = 0xEC;  // 1110 1100
uint TwoBitMask = 0x03;

uint offset = 3;

// Expect 1110 0100
uint result = setBits(test, 0, offset, TwoBitMask);

// Expect 1111 1100
result = setBits(test, 3, offset, TwoBitMask);

// Expect 1111 0100
result = setBits(test, 2, offset, TwoBitMask);
O.B. - 06 Jul 2007 17:23 GMT
Small bug in that last one (bits dropped when shifted).  Let's try
that again:

static uint setBits(uint original, uint newValue, uint offset, uint
mask)
{
 return original & ~(mask << offset) | (newValue << offset);
}

> I've written a small operation that sets/unsets bits within an
> unsigned integer.  Is there a better way to do this?
[quoted text clipped - 21 lines]
> // Expect 1111 0100
> result = setBits(test, 2, offset, TwoBitMask);
Göran Andersson - 06 Jul 2007 20:17 GMT
> Small bug in that last one (bits dropped when shifted).  Let's try
> that again:
[quoted text clipped - 4 lines]
>   return original & ~(mask << offset) | (newValue << offset);
> }

I was just thinking when reading the first post that you should shift
the mask and the value instead of shifting the original. :)

Signature

Göran Andersson
_____
http://www.guffa.com


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.