PDA

View Full Version : Shift Operators (Java)



Lexxuk
16-01-05, 22:27
Ok, I'm having a bit of trouble getting my head around these shift operator things.


A shift operator performs bit manipulation on data by shifting the bits of its first operand right or left. This table summarizes the shift operators available in the Java programming language.

op1 >> op2 shift bits of op1 right by distance op2
op1 << op2 shift bits of op1 left by distance op2
op1 >>> op2 shift bits of op1 right by distance op2 (unsigned)


Each operator shifts the bits of the left-hand operand over by the number of positions indicated by the right-hand operand. The shift occurs in the direction indicated by the operator itself. For example, the following statement shifts the bits of the integer 13 to the right by one position:

13 >> 1;

The binary representation of the number 13 is 1101. The result of the shift operation is 1101 shifted to the right by one position-110, or 6 in decimal. The left-hand bits are filled with 0s as needed.

The way I read it, 13 in binary is 1101, you then move the binary form along op2 (1) places, so 13 >> 1 is 1101 >> 1 = 0110? I dont get it, anyone wanna explain in English what it all is? Binary for 13 is 0011 0001 0011 0011 apparently too, so I'm bloomin confused :confused:

Nidhogg
16-01-05, 22:42
It's pretty simple really. Imagine 13 in 8-bit binary:

00001101

If you shift it right by one then all the bits simply move right; the right-most bit simply drops off and is lost, and the left-most bit is set to 0. So you get:

00000110

...which is 6 in decimal. It's not another representation of 13, it's just 6. So 13 shifted right by 1 bit is 6.

Notice anything about those two numbers, 13 and 6? Shifting a number right by 1 bit is the equivalent of integer dividing by 2 and shifting left is the same as multiplying by 2.

N

Dribble Joy
16-01-05, 23:02
I'm not a coder, I'm an engineer... but surely that is hideously inacurate?

Nidhogg
16-01-05, 23:08
I'm not a coder, I'm an engineer... but surely that is hideously inacurate?
It depends what you're after. If you're writing a calculator then sure, you wouldn't want to use shifting (or its brother, rotation, where the bits that drop off one side get rotated around to the other so you always have the same bits). If you need really reeeeally FAST aproximated division/multiplication then you're in luck. Using bit shifting for maths was one of those assembly tricks you picked up, like XORing the accumulator with itself to set it to 0 (XOR A is a one byte instruction, whereas LD A, 0 is two bytes - one for the load operator and one for the 0 that you're loading).

N

/edit - these operators are usually used for packing things into structures though, not for maths.

retr0n
16-01-05, 23:32
Niddy here is correct, as usual, do you like know everything? Or do you go
around and research it before answering :p lol

And the XOR trick was class.

Nidhogg
16-01-05, 23:39
I've been programming for a while now. ;) Stuff like this takes me back.

N

/edit - back when you had computers with just a few bytes for you to write your code you tended to pick up tricks like that. :)

Lexxuk
16-01-05, 23:46
Ahh I see, not sure I'll ever use bit shifting, but its part of the tutorial

int i = 8;
i >>=2;

value of i is 1000 >> = 0010 so i=2

int i = 17;
i >>=1;

value of i is 10001 >> = 1000 so i=8

w00t, i'm right :D still I really cant think of any reason I'd want to shift bits :confused:

/edit - next exercise:

Exercise: Write a program that tests whether a floating point number is zero. (Hint: You shouldn't generally use the equality operator == with floating point numbers, since floating point numbers by nature are hard to match exactly. Instead, test whether the number is close to zero.)

be back in a few months :lol: :lol:

Nidhogg
16-01-05, 23:58
Ahh I see, not sure I'll ever use bit shifting, but its part of the tutorial

int i = 8;
i >>=2;

value of i is 1000 >> = 0010 so i=2
This isn't correct because you don't specify how many bits you wish to shift by.

i>>=2 - you need: i>>2 = 2

N

retr0n
17-01-05, 00:11
Could u use like:

if ( -0.00000001 < [floating point variable] < 0.00000001 )
{
..... is very damn close to 0.0
}

I got no clue when it comes to Java... But I hope this doc helps:
Java Floating-Point Approximation @ java.sun.com (http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Math.html)

--- EDIT ----

I just found this:



Guidelines for comparing floating point numbers
Because of the unusual comparison behavior of NaN, and the rounding errors that are virtually guaranteed in nearly all floating point calculations, interpreting the results of the comparison operators on floating point values is tricky.

It would be best to try to avoid floating point comparison entirely. This is, of course, not always possible, but you should be aware of the limitations of floating point comparison. If you must compare floating point numbers to see if they are the same, you should instead compare the absolute value of their difference with some pre-chosen epsilon value, so you are instead testing whether they are "close enough." (If you don't know the scale of the underlying measurements, using the test "abs(a/b - 1) &lt; epsilon" is likely to be more robust than simply comparing the difference.) Even testing a value to see if it is greater than or less than zero is risky -- calculations that are "supposed to" result in a value slightly greater than zero may in fact result in numbers that are slightly less than zero due to accumulated rounding errors.

The non-ordered nature of NaN adds further opportunities for error when comparing floating point numbers. A good rule of thumb for steering clear of many of the gotchas surrounding infinity and NaN when comparing floating point numbers is to test a value explicitly for validity, rather than trying to exclude invalid values. In Listing 1, there are two possible implementations of a setter for a property that can only take on non-negative values. The first will accept NaN, the second will not. The second form is preferable because it tests explicitly for the range of values you consider to be valid.

And you can find it
here (http://www-106.ibm.com/developerworks/java/library/j-jtp0114/)

--- EDIT #2

You could use compareTo( ); method for comparing floating point, it's the same
as equals(); but more accurate as I understand it.

Lexxuk
17-01-05, 00:34
This isn't correct because you don't specify how many bits you wish to shift by.

i>>=2 - you need: i>>2 = 2

N

thats the bit that confused me. from the tutorial thing:

>>= used as op1 >>= op2. Equivilent to, op1 = op1 >> op2. >> used as op1 >> op2. Operation is, shift bits of op1 right by distance op2.

so the way I read it, i >>=2 is really i = i >> 2

/edit at above


public class FloatTest {
public static void main(String[] args) {
float f = 100.0f;
float MAX = 0.001f;
float MIN = -MAX;

System.out.print(String.valueOf(f));

if ((f < MAX) && (f > MIN)) {
System.out.println(" is pretty darn close to 0.");
} else {
System.out.println(" is not close to 0.");
}
}
}

save as FloatTest.java
javac FloatTest.java
java FloatTest
apparently, but I'm holding on the Sun tutorial now, its gotten a little complicated so I'm going to read other tutorials and ebooks till I can remember enough stuff to actually make the stuff in the tests :o

Nidhogg
17-01-05, 00:47
I didn't think there was a >>= operator.

N

Lexxuk
17-01-05, 00:54
wont come out right cause of tables but

Operator ..... Use ................Equivalent to
<<= ...... op1 <<= op2 ..... op1 = op1 << op2
>>= ...... op1 >>= op2 ..... op1 = op1 >> op2
>>>= ...... op1 >>>= op2 ... op1 = op1 >>> op2

should work, hopefully. Might be just a Java thing

Lexxuk
17-01-05, 04:50
yay double post!! (no edit :p)

Found this really cool book that so far has been a breeze. Starts off with the hello world

public class HelloWorld
{
public static void main (String [] args)
{
System.out.println("Hello World");
}
}

(From memory that is :D) Then it tells you "learn what you know to print out name, email etc..

so thats System.out.println("Name"); \n System.out.println("Email"); so its cool cause your using what you learnt (easy to remember)

Then it says "ok, arg function!!" System.out.println("Name " +args[0]); so on the cli its java, err, cant remember if its java name class or java class name, but anyhow its a good easy book to go with tutorial, java's pretty easy really :D

Heavyporker
17-01-05, 06:37
I hate Java.


basically flunked it. :(

Arbiter
17-01-05, 07:27
I didn't think there was a >>= operator.

N

Why not? It is pretty much like the +=, the *=, the /=, the -= or the %= operator (there are still more I think), all representing
var1 = var1 {+, *, /, -, %, ...} var2



i>>2 = 2


I think you would get problems when compilating that line as the left hand needs to be a simple variable and java doesn't feel like assigning a value to i in this case. :p

tomparadox
17-01-05, 09:42
Why not? It is pretty much like the +=, the *=, the /=, the -= or the %= operator (there are still more I think), all representing
var1 = var1 {+, *, /, -, %, ...} var2



I think you would get problems when compilating that line as the left hand needs to be a simple variable and java doesn't feel like assigning a value to i in this case. :p
owned :p :lol::rolleyes:


im so lost in this post lol, im more of a gfx design person :/

Nidhogg
17-01-05, 12:25
Java's a new-fangled lanuage as far as I'm concerned. ;) Couldn't find any evidence of those operators in Sun's reference either. I can see why they could exist, I just couldn't see that they actually did exist. :p

N

Lexxuk
17-01-05, 14:05
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/assignment.html

Still have no idea why I'd ever want to shift a bite though, its all double dutch to me at the moment

Darak
17-01-05, 14:52
Still have no idea why I'd ever want to shift a bite though

You use it to do things fast in certain situations, also you use it a lot if you have to pack stuff into a bit stream. Best example would be something like JPG which uses lots of bitwise operations.

Bit operations are the bread and butter of embeded devices, where you have 32k of memory and a processor from the darkages (eg Z80 stuff) a few shifts here and there can save your life.

However in java i guess you would not use bit stuff often. I'm coming to the concluion that more they teach java at university, the less i have to worry about retirement, cos there will be noone left who understands why things work deep down in the code.

Nidhogg
17-01-05, 15:32
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/assignment.html

Ah, didn't see that. Thx.

/me goes back to never having to use Java anyway ;)

N

Lexxuk
17-01-05, 16:11
Ah, didn't see that. Thx.

/me goes back to never having to use Java anyway ;)

N

Java is my stepping stone to learning other languages, one day I'll get the grasp of java, know how to use it and programme in it, then its off to learn other stuff, possibly fully learn php and stuff, still got nothing better to do these days :D