I would like to encode a pair of ints in a double. For example say i wanted to pass a function:
foo(int a, int b)
but instead I want just one double to represent the two ints (ie) :
foo(double aAndB)
Currently I am doing it by having one int on either side of the decimal place (ie 10 and 15 would become 10.15) and then converting it to a stringstream tokenising and extracting the two numbers.
However, this has an obvious flaw when it comes to numbers like 10 and 10 ie it becomes 10.1.
Is there a way to do this through some tricky mathematical method so that I can pass a function a double that represents 2 ints?
Thanks.
Since (usually) a double has 64 bits in it and each int has 32 bits, you’d think that you could just store the bits into the double directly, e.g.:
… and doing that “almost works”. That is, it works okay for many possible values of i1 and i2 — but not for all of them. In particular, for IEEE754 floating point format, any values where the exponent bits are set to 0x7ff will be treated as indicating “NaN”, and the floating point hardware can (and does) convert different NaN-equivalent bit-patterns back to its preferred NaN bit-pattern when passing a double as an argument, etc.
Because of this, stuffing two 32-bit integers into a double will appear to work in most cases, but if you test it with all possible input values you’ll find some cases where the values unexpectedly mutated during their stay inside the double, and came out as different values when you decoded them again.
Of course, you could get around this by being careful only to set the mantissa bits of the double, but that will only give you 26 bits per integer, so you would only be able to store integer values of +/- 33,554,432 or so. Maybe that’s okay, depending on your use case.
My advice is, find a different way to do whatever you’re trying to do. Storing non-floating-point data in a floating point variable is asking for trouble, especially if you want your code to be at all portable.