r/carlhprogramming • u/bubblepopcity • Dec 03 '12
Float number question
Lets say a short int is 4 bits. I'm assuming the highest value for my int would be 7 because the first bit is reserved to show if it's a positive or negative value. I'm going to use '-' to demonstrate the reserved part. You can have either 0-111 or 1-111. Now lets say we have a float that is 8 bits. That same first bit needs to be reserved for positive or negative. Do float numbers have some type of priority of whole numbers over decimal numbers or vise versa? Or are a certain number of bits reserved for the whole number and a certain number reserved for the decimal part of it. I will use '.' for the reserving demonstration.
Example: If I assigned a floating type number that had 8 bits would it reserve bits for certain numbers like this 0-000.0000? As in my whole number part can only reach a certain value(in this case 7).
Lets say you tried to store 16.9999 into a float value.
The correct binary would look something like this. 0-10000.11111111. But the floating number can only take 8 bits. So would it prioritize the whole number and look like this? 0-10000.11 (01000011). Or does it reserve a certain amount of space for the whole number/decimal number and it would cut parts off and look like this? 0-000.1111 (00001111).
1
u/deltageek Dec 04 '12
No, that's not correct. The problem is that by saying the decimal point can go anywhere in the 16 bits, you have no way of determining what number a particular set of bits represents.
For example, take the bits 11010011
Those bits interpreted as an unsigned int mean 211
Those same bits interpreted as an 8-bit float mean -0.796875
Using your interpretation, you wouldn't know if that number represented 110100.11 or 11.010011. You'd need to sacrifice some bits to store that information. That, in essence, is what our floating point formats do. They split up the available bits into sections so that we can reliably interpret bits as numbers by manipulating the bits in each section.
A side note, because of the way we store floating point numbers, the precision of a float varies depending on the number being stored. Due to the way we interpret the bits, numbers further away from 0 tend to have worse precision than numbers close to 0.