Search code examples
swiftbit-shiftsigneduint64

Puzzled with 64-bit UInt right shift acting as signed shift


Why does the right shift behave as follows?

let a: UInt = 0x6177206d, b: UInt = 0x9e3779b1
let m: UInt = a * b

print("""
    let m = \(String(format:"%x", a)) * \(String(format:"%x", b)) = \(String(format:"%x", m))

    m>>4=\(String(format:"%x", m >> 4))
    m>>8=\(String(format:"%x", m >> 8))
    m>>16=\(String(format:"%x", m >> 16))
    m>>32=\(String(format:"%x", m >> 32))
    """)

Produces:

let m = 6177206d * 9e3779b1 = ef1bf05d

m>>4=fef1bf05
m>>8=efef1bf0
m>>16=a4efef1b
m>>32=3c3ca4ef

Solution

  • m0xef1bf05d; it is 0x3c3ca4efef1bf05d.

    The %x is only handling 32-bit values and you're dealing with 64-bit values. Use %lx or String(m, radix: 16) with 64-bit values:

    let a: UInt = 0x6177206d, b: UInt = 0x9e3779b1
    let m: UInt = a * b
    
    print("""
        let m = \(String(format:"%lx * %lx = %lx", a, b, m))
    
        m>>4  = \(String(format:"%lx", m >> 4))
        m>>8  = \(String(format:"%lx", m >> 8))
        m>>16 = \(String(format:"%lx", m >> 16))
        m>>32 = \(String(format:"%lx", m >> 32))
        """)
    

    Or use %016lx if you want to see it zero-padded (making it easier to see the shifting in process), yielding:

    let m = 000000006177206d * 000000009e3779b1 = 3c3ca4efef1bf05d
    
    m>>4  = 03c3ca4efef1bf05
    m>>8  = 003c3ca4efef1bf0
    m>>16 = 00003c3ca4efef1b
    m>>32 = 000000003c3ca4ef