-4

I have the following snippet:

int n = 10;
int k = n>>1;
std::cout<<k;

This prints 5.

I want k to be the last digit in binary representation of n. Like bin(n) = 1010 So, I want k to be 0.

I understand long methods are possible. Please suggest a one liner if possible.

Edit:

After going through the comments and answers, I discovered that there are various ways of doing that.

Some of them are:

k = n%2
k = n&1

Thanks to all those who answered the question. :)

noobita
  • 57
  • 10

2 Answers2

1
int main( )
{
    unsigned int val= 0x1010;
    //so you just want the least siginificant bit?
    //and assign it to another int?
    unsigned int assign= val & 0x1;

    std::cout << assign << std::endl;
    val= 0x1001;
    assign= val & 0x1;
    std::cout << assign << std::endl;
    return 0;
}

UPDATE:

I would add that bit masking is not uncommon with c. I use ints to hold states often

#define STATE_MOTOR_RUNNING     0x0001
#define STATE_UPDATE_DISPLAY    0x0002
#define STATE_COUNTER_READY     0x0004

Then:

unsigned int state= STATE_COUNTER_READY;
if( state & STATE_COUNTER_READY )
{
    start_motor( );
    state|= STATE_MOTOR_RUNNING;
}
//etc...
lakeweb
  • 1,768
  • 2
  • 14
  • 20
  • What's the point of that? I mean, if it was some I/O register, or some serialized form, fine, but for normal code? – spectras Sep 21 '17 at 09:20
  • HI @spectras, I don't see much of a point, I was just answering the op's question. I added the update to try and frame it in a useful manor. – lakeweb Sep 21 '17 at 15:26
0

You aren't going to be able to avoid some calculation.

int k = n % 10;

will get you the last decimal digit, as that assignment gives k the remainder of division by 10.

vacuumhead
  • 449
  • 1
  • 5
  • 15