Reputation: 8269
I have a number and I just want to read the first bit of the number. I do it like below
#include <iostream>
int main(int argc, char*argv[]) {
unsigned int number = 12345; // Some number
int bit_number_to_read = 1;
int mask = 1 << bit_number_to_read;
int masked_n = number & mask;
unsigned int the_bit = masked_n >> bit_number;
std::cout << "The first bit of number contains: " << the_bit << std::endl;
return 0;
}
The above technique works but is it possible to do it in a one liner?
Upvotes: 1
Views: 2547
Reputation: 23832
If it's odd the bit is 1
if it's even the bit is 0
.
So you could do somenthing like:
unsigned int the_bit = number % 2;
If you were considering the possibility of also having negative int
s:
unsigned int the_bit = std::llabs(number % 2);
llabs
because in some machines long
is 32
bits whereas long long
has to be at least 64
bits.
This is valid for 2's complement.
Or of course the bitwise AND
.
unsigned int the_bit = number & 1;
Simple and effective, 1 AND 1
is 1
, 0 AND 1
is 0
.
Upvotes: 3
Reputation: 22394
The easiest way to get least significant bit is to check if number is even (only works with non-negative numbers):
int LSB = number % 2;
If you want to use bitwise operators to be more verbose:
int MSB = number & 1;
Or (maybe even overly verbose, but conveys the meaning "I want bit at position 0"):
int MSB = number & (1 << 0);
To get most significant bit, you need to first learn what is the number of digits in given type representation:
int digits = std::numeric_limits<unsigned int>::digits();
int MSB = number & (1 << (digits - 1))
Note that for signed types this will provide the most significant number bit (ignoring sign bit).
Upvotes: 3
Reputation: 123440
I didn't check carefully if your code is correct. However, writing it in a single line can be just an exercise of replacing equivalent expressions:
unsigned int number = 12346; // Some number
int bit_number_to_read = 1;
int mask = 1 << bit_number_to_read;
int masked_n = number & mask;
unsigned int the_bit = masked_n >> bit_number_to_read;
std::cout << "The first bit of number contains: " << the_bit << std::endl;
std::cout << (masked_n >> bit_number_to_read) << "\n";
std::cout << ( (number&mask) >> bit_number_to_read) << "\n";
std::cout << ( (number&(1 << bit_number_to_read)) >> bit_number_to_read) << "\n";
All the cout
s will print the same result. As you already mentioned in a comment, the first bit you also get via 0x1 & number
.
Upvotes: 2