-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
  • 67
  • 11
  • 6
    you mean `n & 1`? – spectras Sep 20 '17 at 15:17
  • "This prints 5." really? what language is that? – 463035818_is_not_an_ai Sep 20 '17 at 15:17
  • 2
    “This prints 5.” — it doesn’t print anything. To get the low bit of a value, use `whatever & 0x01`. – Pete Becker Sep 20 '17 at 15:17
  • 1
    `k = n & 1` or `k = n % 2`. It's basically [getting a single bit](https://stackoverflow.com/q/8695945/995714) – phuclv Sep 20 '17 at 15:18
  • Yeah. I got the answer. Thanks! :) – noobita Sep 20 '17 at 15:19
  • `n % 2` produces some trouble with negative `n`, it is a bit odd to say that the least significant bit of a negative number is negative 1 – harold Sep 20 '17 at 15:23
  • If you want k to be he last digit in binary representation of n (which is either 0 or 1), you want to know in fact if the number is even or odd ? Is it what you wanted ? if it is the case you can indeed use something line k = n %2 – M. Yousfi Sep 20 '17 at 15:25
  • @Actarus> not always. Sometimes you actually want the bit value (from a bit field, from some I/O port, …). Since OP specifically tagged with bit manipulation I guess that's what he wants. – spectras Sep 20 '17 at 15:44

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,859
  • 2
  • 16
  • 21
  • 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
  • 479
  • 1
  • 6
  • 16