Floating point notation in Swift

I don't understand how floating point numbers are represented in hexadecimal notation in Swift. Apple documentation shows that 0xC.3p0 equals 12.1875 decimal. Can anyone walk me how to do this? I understand that before the hexadecimal value 0xC = 12. 3p0 after the decimal number is where I am at a dead end.

+3


source to share


5 answers


From the documentation :

Floating point literals
...
Hexadecimal floating point literals are prefixed with 0x followed by an optional hexadecimal fraction followed by a hexadecimal digit. A hexadecimal fraction consists of a decimal point followed by a sequence of hexadecimal digits. The exponent consists of an upper or lower case prefix followed by a sequence of decimal digits indicating which cardinality 2 is equal to the value preceding p multiplied by. For example, 0xFp2 represents 15x2 2 which evaluates to 60. Similarly, 0xFp-2 represents 15x2 -2 which evaluates to 3.75.

In your case

  0xC.3p0 = (12 + 3/16) * 2 ^ 0 = 12.1875


Another example:

  0xAB.CDp4 = (10 * 16 + 11 + 12/16 + 13/16 ^ 2) * 2 ^ 4 = 2748.8125

This format is very similar to the %a

printf format (see, for example, http://pubs.opengroup.org/onlinepubs/009695399/functions/fprintf.html ). It can be used to cast a floating point number directly into its IEEE 754 binary representation, see Why does Swift use base 2 for the exponent of hexadecimal floating point values? for more information.

+7


source


Interpret 0xC.3p0

with place value system:

C (or 12) is in the 16^0 place
3 is in the 16^-1 place (and 3/16 == 0.1875)
p says the exponent follows (like the e in 6.022e23 in base 10)
0 is the exponent (in base 10) that is the power of 2 (2^0 == 1)

      



So all together

0xC.3p0 = (12 + (3/16)) * 2^0 = 12.1875

      

+4


source


0xC is 12 as you said. The decimal part is ((1/16) * 3) * 10 ^ 0.

So, you need to take the decimal part and divide it by 16. Then you need to multiply it by 2, raising it to the level of the number after p

0


source


To summarize what I've read, you can see these views like this:

0xC.3p0 = (12*16^0 + 3*16^-1) * 2^0 = 12.1875

      

From Martin R's example above:

0xAB.CDp4 = (10*16^1 + 11*16^0 + 12*16^-1 + 13*16^-2) * 2^4 = 2748.8125

      

0


source


Hexadecimal -(0-9,A=10,B=11,C=12,D=13,E=14,F=15)

and p0

means 2^0

ex: - 0xC = 12

( 0x

prefix represents hexadecimal) After the decimal part, as in 0xC.3p0

, we divide numbers with cardinality 16

So here is 3/16 = 0.1875

why0xC.3p0 = (12 + (3/16) ) 2^0

If it were 0xC.43p0

, then for 4 we would use 4/(16)

, for 3 we would use 3/(16 ^2)

and similarly if the decimal part increases.

ex: 0xC.231p1 = (12 + 2/16 + 3/(256) + 1/(16^3)) 2^1 = 24.27392578125

0


source







All Articles