Why and 1 ( &1) bitwise operation always return 0 or 1
Asked Answered
C

4

5

I just started learning about bit wise operation and want to ask why and 1 ( &1) bitwise operation always return 0 or 1 .

Calcariferous answered 6/1, 2017 at 7:38 Comment(10)
What do you mean by "1 ( &1) bitwise operation"?Ette
I mean any number when and with 1 just return 0 or 1 value ( a & 1 )Calcariferous
What else do you expect it to return? x & 1 returns 1 if the least significant bit of x is 1 else 0. 1 & 1 = 1, 0 & 1 = 0. That's how the operator is defined.Baroscope
Any bit except the last one is 0 because it's 0 in 1. And the last one is the same than in a. That's all.Korikorie
Any number or just 1 and 0?Ette
I'm voting to close this question as off-topic because it's immediately answered by any documentation on the topicKorikorie
4 and any number will NEVER be 5 ... only 4 or 0Merely
Understood, thank for your helpCalcariferous
3 is little more complex with & .... you can end up with 0, 1, 2 or 3 ... with 5 you can end up with 0, 1, 4 or 5 ... with 128, only 0 or 128 ... do you need any more examples?Merely
@Denys Séguret: I just noticed the [javascript] tag on this question. It's not even a JavaScript question lol.Ette
M
12
0 & 0 === 0
0 & 1 === 0
1 & 0 === 0
1 & 1 === 1

therefore any number & 1 will always be either 0 or 1

in binary ... any number

xxxxxxxxxxxxx0

or

xxxxxxxxxxxxx1

where x can be 0 or 1

1 in binary is

00000000000001

so

xxxxxxxxxxxxx1 &
00000000000001 ==
00000000000001

xxxxxxxxxxxxx0 &
00000000000001 ==
00000000000000
Merely answered 6/1, 2017 at 7:44 Comment(0)
H
4

When you perform a & 1 it will always return 0 or 1 depending upon the the last binary digit of a.

Rules:

0 & 0 = 0
0 & 1 = 0
1 & 1 = 1

For example:

a = 5 //5 = 0101
b = a & 1  = 1 //(0101 & 0001)


a = 6 //6 = 0110
b = a  & 1 = 0 //(0110 & 0001)
Hoxsie answered 6/1, 2017 at 7:48 Comment(0)
G
1

This is a bitwise operation. Suppose you take 2 & 1. That would be 10 and 01 in binary. Bitwise AND will give 00. BitWise operations with 1 will give 1 or 0 always because 1 has only a significant unit's place in binary. So it cannot return any value other than a 0 or a 1.

Gwyngwyneth answered 6/1, 2017 at 7:48 Comment(0)
B
0

This can be used to check if an integer is odd or even, returning a 0 for False and 1 for True.

is_odd: 1 for odd , 0 for even

odd = number & 1

is_even: 1 for even , 0 for odd

even = number & 1 ^ 1

Billie answered 15/2, 2022 at 19:14 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Supersensible

© 2022 - 2024 — McMap. All rights reserved.