Geosearchef
Geosearchef

Reputation: 648

Convert float to int bitwise without casting

I'm trying to checksum an array of floats. Therefore I want to convert them to integers bitwise. Is there any fast way to this not manipulating the bytes by myself?

Upvotes: 1

Views: 910

Answers (1)

Andreas Fester
Andreas Fester

Reputation: 36650

You can get the internal, bitwise representation of a float with Float.floatToRawIntBits(). You can then use the returned int to create a checksum:

int checksum = 0;
for (float value : floatArray) {
  checksum += Float.floatToRawIntBits(value);
}

Depending on your use case, you might also use Float.floatToIntBits() which returns the canonical value 0x7fc00000 for all NaN values.

As for the checksum calculation itself, I took the simplest approach of just summing up the values. There are better checksum algorithms which are more robust against specific flipped bit patterns - once you have the int values, you can use them with any checksum algorithm you like (CRC, MD5, SHA2, or something else).

For more information, see for example

Upvotes: 6

Related Questions