lucamegh lucamegh - 11 months ago 61
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.


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)))