JustBlossom JustBlossom - 2 years ago 100
Java Question

Is it possible to perform bit operations on a float in Java?

I have some C code that I am converting to java with a lot of bit level operations.

I have the following code:

float test(float uf) {
return uf ^ (1 << 31);

In the original C code,
was an unsigned value. Since java doesn't have unsigned values, I changed
to a float. Now, I get an error saying that the the first type is a float and the second is an int.

I know there are libraries for it, but I just want to use bit operations just to see what I can do with Java using bit operations out of curiosity.

So, my first question is, is it possible to perform the operation above using Java without using libraries? Second, are there any reasons that you should not work at a bit level in java (besides the fact that there are libraries to do it for you)?

Answer Source

No. We cannot bit shift in floats.

That operation simply flips the 31st bit (starting from zeroth). You can do that in java just fine.

int test(int uf) {
    return uf ^ (1 << 31);

That's your function. The problem you have isn't setting that bit, it's knowing that if that number is negative that its actually a number 0xBFFFFFFF larger than that number. So long as you are consistent with treating ints as a sequence of 32 bits rather than checking it's value at in opportune times, you'll do fine.

If you want 32 bits that give you a proper number. Use a long.

long test(int uf) {
    return (uf & 0x00000000ffffffffL) ^ (1 << 31);

Then you can use it in comparisons properly, and simply cast it to int if you need it as int. Which if we're converting the unsigned to other types is a far superior answer than floats.

Answer 2: We should certainly use bit operations in java as they are really fast in java. Quite often in mission critical code it's best to convert over to them at the critical points, to the point of only using primitives, or even native compiled code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download