convert Hex String to UInt32

Hi,


I observed a strange behaviour with the following code:


UInt32(Float("0x7f000001") ?? 0)
// will return 2130706432
atof("0x7f000001")
// will return 2130706433


Why do I have two different results? Bug?

Actually 0x7f000001 is the Hex representation of the IP address 127.0.0.1

So the correct result should be 2130706433

UInt32("2130706433")
// will return 2130706433


Thanks

Accepted Reply

Why do I have two different results? Bug?

Not a bug. `Float` has only 24-siginificant bits, so cannot represent 32-bit integer value pesicely.

`atof` returns `double`, not `float`.


If you want to get the correct result from a hex represntation, you need to cut "0x" and use `init(_:radix:)`.

let hex = "0x7f000001"
let value = UInt32(hex.dropFirst(2), radix: 16) ?? 0
print(value) //->2130706433

Replies

Why do I have two different results? Bug?

Not a bug. `Float` has only 24-siginificant bits, so cannot represent 32-bit integer value pesicely.

`atof` returns `double`, not `float`.


If you want to get the correct result from a hex represntation, you need to cut "0x" and use `init(_:radix:)`.

let hex = "0x7f000001"
let value = UInt32(hex.dropFirst(2), radix: 16) ?? 0
print(value) //->2130706433

Thanks.


Works with Float64 (so a double) instead of Float or Float32...


UInt32(Float64("0x7f000001") ?? 0)


Float64 has the advantage to return nil if the string is not an actual hex representation.

Hmmm, 0x7f000001 looks like the loopback IPv4 address, 127.0.0.1. Is that why you’re doing this? If so, be aware that standard DNS resolver functions, like

getaddrinfo
, will correctly parse addresses given in hex.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"