• Advertisement
Sign in to follow this  

extracting bits from a signed int

This topic is 4581 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

How do i extract 10011011(signed int) one bit at a time using leftshifting and masking in C? If I shift 10011011 1 to left then it would be 00110110. The 1 at the beginning disappears. Is there a way to assign the disappeared 1 to a variable?

Share this post


Link to post
Share on other sites
Advertisement
You can extract the bit, then shift right (don't know why you would want to shift left). For example:


int number=456;
bool val=number&1;
number>>=1;


This extracts the right-most bit of number and stores it in val, then right shifts number. Then you can extract the next bit, and so on (you can store the total result in an integer by left-shifting it every time you add a bit). That should be enough to get you started!

Share this post


Link to post
Share on other sites
Here's an example of how you might print the binary digits of an unsigned integer in C:
void binary(unsigned value, unsigned bits) {
unsigned bit = 1 << (bits - 1);

do {
if(value & bit) {
putchar('1');
} else {
putchar('0');
}
} while(bit >>= 1);
}
To check the value of a specific bit (the one that's about to disappear in this case) you can simply AND (&) with it and check if the result is non-zero. In assembly language the most significant bit would've been copied into the carry flag automatically.

[Edited by - doynax on October 8, 2005 2:20:28 PM]

Share this post


Link to post
Share on other sites
eleusive: he wants to extract the bits with MSB first, evidently. Doynax's method will work; here's "the other" way, which destroys the variable (also I am making use of templating to avoid having to pass the bit value - note that this may not always be desirable; sometimes you want the runtime flexibility. Also note that of course you can't do this in C++):


template <typename T>
ostream& binary(T value, ostream& os) {
const int bitcount = sizeof(T) * 8;
const int mask = 1 << (bitcount - 1);
for (int i = 0; i < bitcount; ++i) {
// os << ('0' + bool(value & mask)); <-- not sure about this way?
if (value & mask) { os << '1' };
else { os << '0' };
value <<= 1;
}
return os;
}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement