困惑于64位UInt右移作为签名班次

问题描述 投票:1回答:1

为什么右移的行为如下?

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

生产:

let m = 6177206d * 9e3779b1 = ef1bf05d

m>>4=fef1bf05
m>>8=efef1bf0
m>>16=a4efef1b
m>>32=3c3ca4ef
swift bit-shift signed uint64
1个回答
0
投票

m0xef1bf05d;这是0x3c3ca4efef1bf05d

%x只处理32位值,而你正在处理64位值。使用带有64位值的%lxString(m, radix: 16)

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

或者使用%016lx,如果你想看到零填充(让它更容易看到过程中的变化),产生:

let m = 000000006177206d * 000000009e3779b1 = 3c3ca4efef1bf05d

m>>4  = 03c3ca4efef1bf05
m>>8  = 003c3ca4efef1bf0
m>>16 = 00003c3ca4efef1b
m>>32 = 000000003c3ca4ef
© www.soinside.com 2019 - 2024. All rights reserved.