Sign in to follow this  
OleKaiwalker

Bitwise

Recommended Posts

Hey, Just a quick question for you all. Do the two following lines of code result in the same? 1: assert( (block->prevsize & 0x1) == 0x1 && (block->size & 0x1) == 0x1 ); 2: assert( ((block->prevsize & block->size) & 0x1) == 0x1 ); If so, which of the above do you consider the most elegant and "clean"?

Share this post


Link to post
Share on other sites
Yes, they do evaluate to the same thing. Which you can check using:

assert( ((block->prevsize & 0x1) == 0x1 && (block->size & 0x1) == 0x1 ) == ( ((block->prevsize & block->size) & 0x1) == 0x1) );

The most readable version is:

assert( block->ValidSize( ) );

Block::ValidSize( ) {
return (size & prevsize & 0x1) == 0x1;
}

Share this post


Link to post
Share on other sites
Quote:
Original post by Andrew Russell
And then make it even more readable by making a IS_BIT_SET macro.


I usually mandate readable code but really "& 1" is every bit as readable as IS_BIT_SET...

some people thinks diffrently though...

Also note that: assert( size & prevsize & 1) is the same as assert( (size & prevsize & 1) == 1)

Share this post


Link to post
Share on other sites
Quote:
Original post by ToohrVyk
Yes, they do evaluate to the same thing. Which you can check using:

assert( ((block->prevsize & 0x1) == 0x1 && (block->size & 0x1) == 0x1 ) == ( ((block->prevsize & block->size) & 0x1) == 0x1) );

The most readable version is:

assert( block->ValidSize( ) );

Block::ValidSize( ) {
return (size & prevsize & 0x1) == 0x1;
}


and mark that method as const so that people feel comfortable using it in an assert:)

Cheers
Chris

Share this post


Link to post
Share on other sites
Or, organized another way around, you could do this:


// Useful for other situations too :/
inline bool is_set(int value, int bit) {
return (value & (1 << bit)) != 0;
}

// now instead of writing a bunch of asserts that call a function,
// we just write a bunch of calls to the function:
inline void Block::debug_checkSize() const {
assert(is_set(size, 0));
assert(is_set(prevsize, 0));
}
// which in release mode should still disappear completely.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this