lucamegh lucamegh - 1 year ago 122
Swift Question

Crash on UInt64 bitwise operation in Swift

I need to execute this function to get the lsb from an unsigned 64 bit integer but the operation fails. I'm not very good at bitwise operations; could someone give me a hand?

func lsb(id: UInt64) -> UInt64 {
return UInt64(Int64(id) & -Int64(id))

Thank you.

Answer Source

You need to avoid overflow in 3 types of operations:

  • UInt64 to Int64
  • negation
  • Int64 to UInt64

All above changed to overflow-free operations, your code becomes as:

func lsb(id: UInt64) -> UInt64 {
    return UInt64(bitPattern: Int64(bitPattern: id) & (0 &- Int64(bitPattern: id)))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download