Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Floating point hex notation in Swift

Tags:

hex

swift

I don't understand how floating point numbers are represented in hex notation in Swift. Apple's documentation shows that 0xC.3p0 is equal to 12.1875 in decimal. Can someone walk me through how to do that conversion? I understand that before the decimal hex value 0xC = 12. The 3p0 after the decimal is where I am stumped.

like image 644
Michael Spears Avatar asked Dec 05 '22 22:12

Michael Spears


1 Answers

From the documentation:

Floating-Point Literals
...
Hexadecimal floating-point literals consist of a 0x prefix, followed by an optional hexadecimal fraction, followed by a hexadecimal exponent. The hexadecimal fraction consists of a decimal point followed by a sequence of hexadecimal digits. The exponent consists of an upper- or lowercase p prefix followed by a sequence of decimal digits that indicates what power of 2 the value preceding the p is multiplied by. For example, 0xFp2 represents 15 × 22, which evaluates to 60. Similarly, 0xFp-2 represents 15 × 2-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 specify a floating point number directly in its binary IEEE 754 representation, see Why does Swift use base 2 for the exponent of hexadecimal floating point values? for more information.

like image 88
Martin R Avatar answered Dec 22 '22 04:12

Martin R