Erik Price
Posts: 39
Nickname: erikprice
Registered: Mar, 2003
|
|
Re: >> operator and 0xff
|
Posted: May 2, 2003 10:29 AM
|
|
> What exactly does the >> operator do?
Ugh. I have heard that it is useful in low-level programming when you are dealing with memory registers, etc. Provides a convenient shorthand to determine the "next" (or some other) register, the offsets of which are measured in bits (so if you need to know the bit depth of a register that is 4 places from where you are, you can just use >> 4).
Java's strength is letting you code at a higher level of abstraction, so you will probably rarely see it in Java. (Disclaimer: sure there's going to be an exception to this.) It's more common in C programs. The only time I ever had to use it was when I took the SCJP.
To answer your question, the >> ("right shift") operator accepts two operands. The operand on the left is the integer to operate upon. This integer's bits are "shifted to the right" a number of times equal to the right operand.
So when you see 5 >> 2, then the integer 5's bits are shifted to the right three times. In order to visualize what's really happening, you have to first convert the numbers to binary. The binary form of 5 is 101. And in Java, an integer has 32 bits, but the leftmost bit simply indicates if it's a positive or negative integer. So technically, the integer 5 is equivalent to: 00000000000000000000000000000101
So what happens if you were to take each digit in this number and shift it to the right two times (5 >> 2)? By "shift it to the right", I mean you literally move each digit over by one place to the right. The result would be: 0000000000000000000000000001.01
Now, since this is an integer, there cannot be a decimal point or any number after it. So you're left with 0000000000000000000000000001
Converting this number back from binary to decimal numbers results in a 1. So, 5 >> 2 == 1.
Kind of a pain, huh? Old-school hackers can do a better job than me of explaining when you'd want to use this. Like I said, it's only useful in Java on the SCJP (in my experience).
> I have this code, and the part int is baffling me. also > what is the necessity of using the 0xff instead of 255?
It's just another way of writing it. I don't know why it was used, probably depends on your context.
|
|