If I had a integer n, what does the statement n>>=1 do? convert n to binary, then shift to right one bit? or n stays in decimal format then gets shifted? Thanks.
This is a discussion on what does this statement do? within the C Programming forums, part of the General Programming Boards category; If I had a integer n, what does the statement n>>=1 do? convert n to binary, then shift to right ...
If I had a integer n, what does the statement n>>=1 do? convert n to binary, then shift to right one bit? or n stays in decimal format then gets shifted? Thanks.
Convert to binary? Numbers are always stored like that. There is nu such thing as converting a variable to decimal or hex, they are always stored as binary numbers. The numerical base does only matter when you convert the int to a string.
To answer your question: n>>=1 shifts the bits of n to the right one bit.
Binary (base 2) is just a way of representing data, as decimal (base 10) and hexadecimal (base 16) are.
So n can be represented at a bit-level in binary, everything can.
n >> 1 Will shift every bit in n one position right...
for example, if n = "0100 0101".
then after n >> 1, n = "0010 0010"
As you notice, 0 is used as padding...
You may like to read: http://www.cprogramming.com/tutorial...operators.html
Being picky...
For any integer n and b, when n >>= b is executed, n will be right shifted b bits and assigned the result. You will not notice a change in n's radix. All integers have a binary format in memory anyway.
Sorry to interject, is that the C equivalent for the ASM command SHR?
Yes, except, the result isn't assigned.
This leads be to a related question,
how does cin and cout work? is << and >> not bitshift left/right? Just curious...
I've searched for such an explanation with no results.
Depends upon if the n is signed or not.
If n is signed:Code:n>>=1
If n is unsigned:Code:mov eax, n sar eax, 1 mov n, eax
<< and >> are just operators. In C++, you can overload operators. Since it wouldn't make as much sense to bit shift streams, they've been overloaded to accept input and output, respectively.Code:mov eax, n shr eax, 1 mov n, eax
Ah, me see. Thanks