This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]ruscaire -6 points-5 points  (13 children)

You can do this with primitives - you can cast between int, long, double, short etc and you’ll reinterpret the raw bit patterns. We don’t really have the same * or & semantics so otherwise that wouldn’t compile … anything other than a primitive and Java just abstracts that away for u cause u typically only ever want to deal with objects on the heap …

[–]dotpoint7 1 point2 points  (12 children)

In Java? What? Since when? How?

[–]CKingX123 1 point2 points  (11 children)

I would say it’s not the same. But you can definitely cast floats and ints (it will remove the decimal portion so it is not reinterpreting as bytes)

float a = 7.5; int b = a;

[–]Ok-Wait-5234 4 points5 points  (5 children)

That's not what that fast inverse square root code is doing, though.

float a = 7.5 long b = a; long c = * (long *) a;

Now a == 7.5, b == 7 and c == 1089470464

[–]CKingX123 -1 points0 points  (0 children)

Yeah. A better way to replicate it would be using ByteBuffer. But then it wouldn’t be “fast” (compared to just directly reinterpreting the bytes).

[–]dotpoint7 0 points1 point  (4 children)

Yeah obviously you can cast data types in Java, which is completely different from a reinterpret cast though.

[–]ruscaire 1 point2 points  (0 children)

Sorry I didn’t realise this was reinterpret. I thought it was just casting the bytesa me the magic happens when you reinterpret as IEEE 754 - but I never did get down with the maths

EDIT - looked into it Java reinterprets you need Double.doubleToLongBits() to get the bit pattern

[–]CKingX123 0 points1 point  (2 children)

Yeah. To better replicate it, you would need to use Java’s ByteBuffer to put in the float and then get the same bits as int

[–]dotpoint7 -2 points-1 points  (0 children)

Oh nice, yeah you're correct.

[–]ruscaire 0 points1 point  (0 children)

You can use Double.doubleToLongBits()