Here is a small programming brain teaser for the weekend:
ufis an unsigned integer with 64 bits that holds the IEEE-754 representation for a binary floating point number of that size.
The questions are:
ufrepresents an integer number?
2. How to serialize the absolute value of such an integer number in the minimum number of bytes possible, using big-endian ordering and the 8th bit as a continuation flag? For example,
float64(1<<70 + 3<<21) serializes as:
The background for this problem is that the current draft of the strepr specification mentions that serialization. Some languages, such as Python and Ruby, implement transparent arbitrary precision integers, and that makes implementing the specification easier.
For example, here is a simple Python interactive session that arrives at the result provided above exploring the native integer representation.
>>> f = float((1<<70) + (3<<21)) >>> v = int(f) >>> l = [v&0x7f] >>> v >>= 7 >>> while v > 0: ... l.append(0x80 | (v&0x7f)) ... v >>= 7 ... >>> l.reverse() >>> "".join("%02x" % i for i in l) '8180808080808083808000'
Python makes the procedure simpler because it is internally converting the float into an integer of appropriate precision via standard C functions, and then offering bit operations on the resulting value.
The suggested brain teaser can be efficiently solved using just the IEEE-754 representation, though, and it’s relatively easy because the problem is being constrained to the integer space.