Checking set bits

Started by
4 comments, last by Taralieth 19 years, 11 months ago
I have a problem right now. I was wondering if anyone knows how to check what bits are set in a variable of type byte. For example, byte variable is obviously composed of 8 bits. So lets say that value of the byte variable is 200 which is 11001000 in binary and therefore, bits 1, 2 and 5 are set since they have a value of 1 whereas the other bits are all 0. But how would i do this using programming code? A solution using java is prefered but any help is appreciated.
Advertisement
You can use the bitwise AND operation. Say you want to check whether the 4th bit is set (I mean 4th from the end, not from the front). The number which has only this 4th bit set is 00001000 in binary, or 8. Thus check whether (yourByte & 8) != 0. (Since 8 has all bits 0 except for the 4th one, this will only be true if the 4th bit of your number is 1). In general, to check the nth bit, check whether (yourByte & (1<<(n-1)) != 0. (The << operator is bitwise left shift, so 1<<(n-1) is 1 followed by n-1 zeros in binary).

[edited by - Matei on May 20, 2004 7:40:18 PM]
The C++ standard library has a std::bitset that you can use.

daerid | Legends | Garage Games | Spirit | Hapy | Boost | Python | Google
"Doomed to crumble, unless we grow, and strengthen our communication" - Maynard James Keenan, Tool
daerid@gmail.com
quote:Original post by Taralieth
I have a problem right now. I was wondering if anyone knows how to check what bits are set in a variable of type byte.
For example, byte variable is obviously composed of 8 bits. So lets say that value of the byte variable is 200 which is 11001000 in binary and therefore, bits 1, 2 and 5 are set


These are normally considered bits 7, 6 and 3.

quote:since they have a value of 1 whereas the other bits are all 0. But how would i do this using programming code? A solution using java is prefered but any help is appreciated.


if ((x & (1 << 3)) != 0) { // bit 3 is set }if ((x & (1 << 1 || 1 << 6)) != 0) { // bit 1 OR bit 6 is set }if ((x & (1 << 1 || 1 << 6)) == (1 << 1 || 1 << 6)) { // bits 1 AND 6 are set }int b = 0;for (int i = 0; i < 32; i++) b += (x & (1 << i)) >> i;// now b holds the number of set bits in x.// Adjust the loop limit according to the size of x.  


[edited by - Zahlman on May 20, 2004 11:00:53 PM]
hello. thx for the response. I have one more question. I''m just attempting to make my own bittorrent client (just to learn more about network coding) and it says that "The high bit in the first byte corresponds to piece index 0"
What part of the byte is considered the high bit? if the byte was 10000001, would the left most bit be considered the high bit or is the right most bit considered the high bit?
The "high bit" is the one of most significant value; hence the name. So for a byte, use 1 << 7 (also spelled "128" for people who like writing powers of 2 manually).

This topic is closed to new replies.

Advertisement