Reputation: 45
In c/c++, one can do things like
float b = 3.;
int a = *(int*)&b;
I want to do the same thing in java, is it possible and if so, how?
Thank you.
Upvotes: 1
Views: 1261
Reputation: 835
Java implements everything based on pointers. So any object variable in Java will be passed as pointer reference. They made it invisible to Java developer. To convert from float or double to int, you can simply try
double b = 3.0;
int a = (int)b;
Be aware that if b = 1.x then a = 1
Upvotes: 0
Reputation: 41200
Pointers
are not available in java. You have to work with Object
.
Float f = new Float(3.0);
Integer i = Math.round(f);
Upvotes: 2
Reputation: 10497
There is no POINTER
kind of thing in JAVA. JAVA has a feature called Memory Management or say GC(Garbage collector) to handle all the memory related operations for you. You are not allowed to access any memory block by using memory address.
Upvotes: 3
Reputation: 138051
Java doesn't have pointers. For this specific case, you can use Float.intBitsToFloat
(and Float.floatToIntBits
for the other way; Double
also has similar methods). There is, however, no way to do funkier "conversions".
Upvotes: 4