mercredi 23 septembre 2020

Read first bit of a number in one line

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;
}

Above technique works but is it possible to do the above in a one liner?

Aucun commentaire:

Enregistrer un commentaire