hamster on wheels
hamster on wheels

Reputation: 2893

Find float type's memory format

How to find the memory format of float and double types?

I mean the numbers of bits for sign, exponent, and fraction.

Upvotes: 1

Views: 151

Answers (2)

Malcolm McLean
Malcolm McLean

Reputation: 6404

To save floating point numbers to disk in a cross platform manner, look up my github project

https://github.com/MalcolmMcLean/ieee754

I've also put in functions for reading binary integers portably, as it is slightly more involved than appears at first sight.

If you want to test memory format, you need to create floats with certain strategic values, then query the bit patterns. Zero should be all bits zero and a special case, unless you're on weird and wonderful hardware. 1 and -1 should differ by one bit, which is you sign bit. 2 and 1 should differ in the exponent, and testing powers of two should tell you the exponent bits and when they run out. Test powers of powers of two for speed.

You can then get the mantissa by storing 1 off a power of 2, e.g 3, 7 and so on.

By probing it you can build up a memory pattern, but it's almost always IEEE 754.

Upvotes: 1

eerorika
eerorika

Reputation: 238411

I mean the numbers of bits for sign, exponent, and fraction.

You can use std::numeric_limits<T>::digits to get mantissa bits, std::numeric_limits<T>::is_signed to get the sign bits.

You and deduct their sum from sizeof(T)*CHAR_BIT to guess the exponent digits, but this may not be correct if the type has padding. This is typical for long double for example.

Find float type's memory format

Of course, not only the number of bits matter, but also the order. These functions do not help you with that. They also assume that std::numeric_limits<T>::radix == 2.

For the exact format, you will have to consult the manual of the cpu architechture.


I want to save floating point numbers to hard disk and wonder if there is a good way to make the file cross platform.

The most typical solution is to convert the floating point to a textual representation when saving to disk: 0x1.8p+0. It's not most efficient, but it is portable (although, you do have to decide what character encoding the file is going to use, and if that is not native to the system, there needs to be a conversion).

Upvotes: 2

Related Questions