programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Difference Between "a>>b" and "a>b"

Ranch Hand
Posts: 100
Hi guys,

I would like to find out if u all know the difference between "a>>b" and "a>b" in the if condition.

1)

if (a>>b)
{
}

and

2)

if (a>b)
{
}

regards
KKH

Ranch Hand
Posts: 130

Originally posted by koh khai huat:

if (a>>b)
{
}

This is actually right shift. It is a bitwise operator. It doesn't do any kind of comparison. Let me explain in brief,

a >> b

means, shift by 'b' bit right of binary of 'a'

Hope you've got the idea.

Ranch Hand
Posts: 62
There's also a >>> operator in Java, which is slightly different than >>. >>> doesn't preserve the sign, where >> does. For instance: (I'm using 4 bit numbers for simplicity)

2 >> 1 = 1, since 2 = 0010 and when shifted right 1, it becomes 0001
-1 >> 1 = -1, since -1 = 1111 and when shifted right 1, it becomes 0111. However, -1 is negative, and so the high bit (sign bit) gets reset. So the number becomes 1111, or -1

2 >>> 1 = 1 (by above)
-1 >>> 1 = 7 (by above)

It's a little hard to get used to at first, but bit shifts are almost always used to make bit masks, or divide/multiply by powers of two quickly. For example:

5 << 1 = 5 * 2
5 << 2 = 5 * 4
5 << 3 = 5 * 8
...

This should be obvious when you consider what each place in a decimal number really means:

2 = 2*10^0 = 2
20 = 2*10^1 = 2*10
200 = 2*10^2 = 2*100
...

EDIT: Forgot to mention, << is the opposite of >>, or more exactly >>> since << does not preserve sign
[ February 07, 2006: Message edited by: Jeremy Tartaglia ]

Ranch Hand
Posts: 30
Hi,

Suppose a=2, and b=3;
if i say ,
if(a>b)
{...........
}// it will check whether value of a is greater than b or not. In above case a is less then b, hence condition fails and it will not enter into {..}

But if i write a>>b,
a=2 i.e in binary representation a=00000010,
b=3 i.e in binary representation b=00000011,

if i say a>>1, it will right shift the content once i.e new value of a=00000001 and the last bit is lost.

i suggest you to go through some examples.

lowercase baba
Bartender
Posts: 12601
50
i haven't tried it, but i doubt

will even compile. what's inside the parens must be, or evaluate to, a boolean. a>>b should evaluate to an int (or whatever type a and b are). therefore, the compiler should complain.

Ranch Hand
Posts: 1780
I thought a>>b meant "a is much bigger than b"

 Too many men are afraid of being fools - Henry Ford. Foolish tiny ad: The WEB SERVICES and JAX-RS Course https://coderanch.com/t/690789/WEB-SERVICES-JAX-RS