Search code examples
swiftsyntaxscientific-notation

Swift scientific notation in base 16


I'm new in Swift language and playing with it. I know in most languages 1.5e3 means 1.5 * 10 ^3 and this is true in Swift. However, when it comes base 16, I have difficulty in understanding it. Below are 2 examples, hope someone can explain what they are:

println(0x12e3)
println(0x12p3)

The results are:

4835
144.0

Solution

  • The first example is not using scientific notation - because e is a valid digit in hexadecimal, this is the number 12E3, which is 4835 in decimal.

    (1 * 4096) + (2 * 256) + (14 * 16) + (3 * 1) = 4835
    

    The second example is the hex number 12 (18 in decimal) multiplied by a binary exponent (2 ^ 3), i.e. 8.

    8 x 18 = 144
    

    This notation is described in the Swift language documentation.