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.
source to share
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.
source to share
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
source to share
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
source to share