January 31st, 2014, 07:00 AM

(x & 1); x>>=1; dont get it.
Hi. :hi:
My first post here.
I have learned some bitprogramming and i can use it ok.
But heres one thing i dont get.
"something" = (x & 1);
x >>=1;
(x & 1) means that x is high or 1?
and then x>>=1 goes 0 again?
is that correct?
Does it mean that "something" is now 1?
switched on?
and then x >>=1;
means that "something" is going back to 0?
switched off again?
so its the same as:
"something" = 1;
"something" = 0;
January 31st, 2014, 09:02 AM

Howdy and welcome. :)
I notice that the code in your question title and the code in your post while similar, are rather different. Consequently, I may be more verbose than necessary.
Your understanding of bitwise operations seems a little shaky, though its relatively straightforward and quite easy to explain.
As an example, consider the following code, with a random value for X.
Code:
int something; // something = ?
int x = 10; // x = 10
something = x & 1; // something = 0
x >>= 1; // x = 5
Now again, in binary instead of decimal:
Code:
int something; // something = ?
int x = 00001010; // x = 10d
something = 00001010 & 00000001; // something = 0 (0&1 = 0)
x >>= 1; // x = 00000101 (5)
So, hopefully you can see that it's a simple bitwise AND, then a simple bitwise SHIFTRIGHT. ShiftRight & ShiftLeft work just the same as they do for decimal numbers (though the operation doesn't have an equivalent outside the computing realm). I.e 1 shiftleft a single digit gives 10. The difference is equal to 'the range of values of a digit' multiplied by the original digit. So, since we're working in base10, each shift left or right results in a multiplication or division of 10, respectively. Consider the series: 1, 10, 100, 1000
Now, the bitwise shift of a binary number is done in base2  each digit has a maximum of 2 values, so we multiply or divide by 2. I.e 0001(1), 0010(2), 0100(4), 1000(8)
As for the binary AND, you can use the following truth table:
Code:
A  B result

0  0 0
0  1 0
1  0 0
1  1 1
February 1st, 2014, 09:03 AM

ah, so "x & 1" is Another way to write "x & 0x01"?
I got confused... :)
thx a lot for your answer.
Even if you know something you still can get confused sometimes... :)
February 1st, 2014, 09:14 AM

Originally Posted by grane
ah, so "x & 1" is Another way to write "x & 0x01"?
I got confused... :)
thx a lot for your answer.
Even if you know something you still can get confused sometimes... :)
You're welcome.
Yup  0x01 and 1 and 01 are all equivalent..
0x01 is using base16 notation (the 0x prefix indicates this) and 1 is using base10 notation (the lack of a prefix/suffix indicates this)
So, I could just as easily write 0x10 as I could write 16 or (confusingly) 020  the '0' prefix indicates that this is base8.
Likewise 0xFF is equivalent to 255 (0xF * 16 + 0xF = 15*16 + 15)
These two links explain it reasonably:
http://www.cs.umd.edu/class/sum2003/.../hexoctal.html
http://www.cplusplus.com/doc/hex/