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?
Asked
Active
Viewed 858 times
1
-
Something like [`Float.floatToRawIntBits()`?](https://docs.oracle.com/javase/8/docs/api/java/lang/Float.html#floatToRawIntBits-float-) – Andreas Fester Apr 13 '16 at 18:07
-
Yes, thanks! Actually, what is the difference between floatToIntBits() and floatToRawIntBits()? The handling of NaN? – Geosearchef Apr 13 '16 at 18:11
-
Yes, if the actual number is representing a `NaN` value then the two methods return different values. `floatToIntBits()` returns the same canonical value for all possible `NaN` values while `floatToRawIntBits()` returns different values, depending on the actual `float` `NaN` value. – Andreas Fester Apr 13 '16 at 18:15
1 Answers
6
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

Community
- 1
- 1

Andreas Fester
- 36,091
- 7
- 95
- 123
-
1I suggest using a multiplier to create a simple hash. But this does the job +1 – Peter Lawrey Apr 13 '16 at 18:37