Reputation: 4070
Why does this return 10010 instead of 00001?
0110 >> 2 // 10010
I thought the bits would be shifted to the right 2 times, but they're not. The output I expected was 0001
or 1 but I got 0 instead. Why is this?
Upvotes: 0
Views: 82
Reputation: 54551
Your number is not being interpreted as binary, but rather octal (base 8). Octal 0110
is 72
in decimal, or 1001000
in binary. When you right shift by 2, that becomes 10010
as you are seeing.
It's common in programming languages that a leading zero means octal. Depending on the language you are using, there may or may not be a way to specify a binary literal.
A more universal way to express a binary number would be using hex since each nibble (hex digit) is exactly 4 bits.
0 0000
1 0001
2 0010
3 0011
4 0100
5 0101
6 0110
7 0111
8 1000
9 1001
A 1010
B 1011
C 1100
D 1101
E 1110
F 1111
So, to make 0110 (binary) we'd use 0x6. To make 01101101 we'd use 0x6D.
Upvotes: 1
Reputation: 179452
0110 is an octal constant because it starts with a zero:
>>> 0110
72
>>> 0110 >> 2
18
>>> bin(_)
'0b10010'
This is Python, but the same is true of many other languages with octal constants (Java, C, JavaScript, ...). Not all languages provide binary constants. If you don't have them, you can use hexadecimal constants instead (0b0110 is 0x6, for example).
Upvotes: 2